How to trap key press to accept only numeric keys


  Hello word.  Lets talk about trapping keys.  For example I have a TextBox name tbStudentId and this is where the user enters a student's ID number.  Now, you want it to accepts numbers but not letters.  How can we do that?

Try this line of code:

Public Class Form1

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        e.Handled = allownumeric(e.KeyChar)
    End Sub

    Public Function allownumeric(ByVal key As String) As Boolean
        Dim numbers As String = "0123456789"
        If key <> Chr(8) Then
            If numbers.Contains(key) Then
                allownumeric = False
            Else
                allownumeric = True
            End If
        End If
    End Function
End Class


   What doees Chr(8) mean? It's the backspace.  Your text box must also include backspace to allow changes in input.

   You may download the program here.

Arnel Isiderio Robles Software Developer

I am passionate about doing something good in the community and sharing my thoughts on different areas ranging from programming to community development. I am interested in developing my skills and use it for the greater good.