VB.net Need Text Box to Only Accept Numbers

You can do this with the use of Ascii integers. Put this code in the Textbox’s Keypress event. e.KeyChar represents the key that’s pressed. And the the built-in function Asc() converts it into its Ascii integer.

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    '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

Leave a Comment