VB.NET - Number(10,2) 的 DataGridView 子字符串单元格

VB.NET - DataGridView substring cell for Number(10,2)

我有一个带有一列的 DataGridView,用户可以在其中插入双精度值。在我插入数据库之前,我必须控制单元格值,因为 table 这个字段有一个数字 (10,2) 数据类型。

我现在的代码:

Dim length As Integer = Nothing    
Dim row As Integer = DTG.CurrentCell.RowIndex
Dim column As Integer = DTG.CurrentCell.ColumnIndex()

With DTG(row).Cells(column)
    length = Len(.Value)
    If Not IsNothing(.Value) Then
            If Not IsNumeric(.Value) Then
                    .Value = 0
            End If

            If length > 10 Then
                    .Value = .Value.SubString(0, 10)
                    If .Value.Contains(".") Then
                        .Value = .Value.SubString(0, 9)
                    End If
            End If
    End If
End With

长度法在这里不合适,因为如果我的单元格包含“.”,长度会增加。

示例:

1234567891 => length = 10 => insert : 1234567891

123456789.1 => length = 11 => insert : 123456789

在第二种情况下,我需要插入123456789.1

有人可以告诉我吗?谢谢

您可以使用 .Value.IndexOf(".") 获取小数点前的位数 (<= 10)。

我最终决定使用单元格值。

If .Value > 99999999.99 Then
    .Value = Convert.ToDouble(.Value.SubString(0, 8))
End If

我把样式格式改成了"N2",所以用户不能写超过2位小数:

.ValueType = GetType(Double)
.Style.Format = "N2"

我还找到了另一种方法,我可以像屏蔽文本框一样格式化我的列。我稍后会尝试这个解决方案。

编辑: 以前的答案很糟糕,但它帮助了我一段时间。我找到了一种更好的方法来处理我的问题。我创建了一个函数来检查小数点前的位数,如果长度大于 8,则其 return False :

Public Function numberDigitsBeforeDecimal(ByVal montant As Double) As Boolean
    Dim beforeDigit As String = montant.ToString.Substring(0, montant.ToString.IndexOf("."))

    If beforeDigit.Length > 8 Then
        Return False
    Else
        Return True
    End If
End Function

如果我没记错的话,数据类型为 number(10,2) 的数据库字段意味着它可以携带最大值 99999999.99,使用这个你可能会改变你的代码看起来像

Dim dbMaxNum As Decimal = 99999999.99

With DTG(row).Cells(column)
    If Not IsNothing(.Value) Then
        If Not IsNumeric(.Value) Then 
            .Value = 0
        Else
            .Value = Math.Min( _
                        dbMaxNum, _
                        Math.Round(CDec(.Value), 2, MidpointRounding.AwayFromZero))
        End If
    End If
End With

我们首先将 .Value 舍入到两位小数,然后我们选择结果与您的数据库字段可以容纳的最大值之间的最小值 (99999999.99)

选项 MidpointRounding.AwayFromZero 是为了防止意外的舍入结果,例如 32.625 舍入到 32.62this question 中提出的问题)。