我有一个带有一列的DataGridView,用户可以在其中插入双精度。在插入数据库之前,我必须控制单元格值,因为该表具有此字段的数字(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)。
没记错的话,数据类型为 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.62
(这个问题中提出的问题)。
我最终决定使用单元格值。
If .Value > 99999999.99 Then
.Value = Convert.ToDouble(.Value.SubString(0, 8))
End If
我将样式格式更改为"N2",因此用户不能写入超过 2 位小数:
.ValueType = GetType(Double)
.Style.Format = "N2"
我还找到了另一种方法来做到这一点,我可以像蒙版文本框一样格式化我的列。我稍后会尝试这个解决方案。
编辑:之前的答案很糟糕,但它帮助了我一段时间。我找到了处理问题的更好方法。我创建了一个函数来检查小数点前的位数,如果长度大于 8,则返回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