Search code examples
vb.netdatagridviewsubstringvariable-length

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


I have a DataGridView with a column where the user can insert double. I have to control the cell value before i insert in my database because the table have a number(10,2) datatype for this field.

My current code :

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

The length method is not appropriate here, because if my cell contains ".", the length increases.

Examples :

1234567891 => length = 10 => insert : 1234567891

123456789.1 => length = 11 => insert : 123456789

In the 2nd case, i need to insert 123456789.1

Can someone advise me ? Thank you


Solution

  • I finally decided to work with the cell value.

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

    I changed the style format to "N2", so the user can't write more than 2 decimals :

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

    I also found another way to do this, i could format my column like a masked textbox. I'll try this solution later.

    EDIT : The previous answer is pretty bad but it had helped me for a while. I found a better way to handle my problem. I created a function that check the number of digits before the decimal, and if the length is higher than 8, its 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