KnightsOfTheRoun
KnightsOfTheRoun

Reputation: 155

Prevent non-number values from being typed into a datagridview column

I have a DataGridView on my form which 3 columns. I need the 2nd column to only allow numbers to be typed into it. I have code I have used for a text box:

Private Sub NumbersOnly(ByVal sender As System.Object, ByVal e As system.Windows.Forms.KeyPressEventArgs)
    '97 - 122 = Ascii codes for simple letters
    '65 - 90  = Ascii codes for capital letters
    '48 - 57  = Ascii codes for numbers

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If
End Sub

I am trying to find out what event I could use to do the same process within my DataGridView. I have tried the keypress event and it does not work. Any suggestions on how to prevent non-numbers from even being typed. Thanks all!

Upvotes: 0

Views: 284

Answers (1)

Victor Zakharov
Victor Zakharov

Reputation: 26454

Instead of manually validating it to contain numbers, set a data type of the column to be numeric. Then it will be auto-validated. Don't try to handle it via keypress, keydown, cause then it's also copy/paste (CTRL+C/CTRL+V), mouse right-click and other possible ways to put bad data.

Upvotes: 1

Related Questions