Search code examples
vb.netdatagridviewcellkeypress

How to allow one period only in Datagridview Cell in vb.net


I am trying to make my datagridview cell to accept numbers only and a single period.

so far I have successfully made it to accept numbers only, here is the code:

    Select Case e.KeyChar
        Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", vbBack
            e.Handled = False
        Case Else
            e.Handled = True
    End Select

In my textbox, I will also accept numbers and single period only, here is the code:

    Select Case e.KeyChar
        Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", vbBack
            e.Handled = False
        Case Else
            e.Handled = True
    End Select


    If (txt1.Text.IndexOf(".") >= 0 And e.KeyChar = ".") Then e.Handled = True

All of the code are in KeyPress event. I have no idea how to make my datagridview cell accept single period only.

Thank you for the help.


Solution

  • The event dealing better with what you want is CellValueChanged: it will just check the definitive value and, eventually, correct it. Also you can rely on IsNumeric to quickly find valid numbers. Sample code for DataGridView1:

    Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    
        If (e.RowIndex >= 0 AndAlso e.ColumnIndex >= 0) Then
    
            Dim curVal As String = DataGridView1(e.ColumnIndex, e.RowIndex).Value.ToString()
            If (curVal.Trim().Length > 0) Then
    
                If (curVal.Contains(".")) Then
                    'Checking whether the given entry has more tha one period
    
                    Dim temp() As String = curVal.Split("."c)
                    If (temp.Length > 2) Then
                      'More than one period
                       DataGridView1(e.ColumnIndex, e.RowIndex).Value = temp(0) & "." & temp(1)
                    ElseIf (Not IsNumeric(curVal)) Then
                       'Is not numeric
                       DataGridView1(e.ColumnIndex, e.RowIndex).Value = ""
                    End If
    
                ElseIf (Not IsNumeric(curVal)) Then
                    'Any other non-numeric entry
                    DataGridView1(e.ColumnIndex, e.RowIndex).Value = ""
                End If
    
           End If
    
        End If
    
    End Sub
    

    Bear in mind that IsNumeric will catch any non-numeric situation (for example: 1.32.52), thus I have included a pre-condition to check specific cases with more than one period to show you how you can deal with different situations (you might analyse the whole string to remove specific parts, instead just deleting the whole cell).