Thursday, August 25, 2011

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.

FREE TEXT