How To Validate Numbers in TextBox

Visual Basic Topics
Post Reply
User avatar
gougou
Corporal
Corporal
Posts: 7
Joined: Wed Mar 17, 2010 9:36 pm
Location: Indonesia

How To Validate Numbers in TextBox

Post by gougou » Wed Mar 17, 2010 11:19 pm

This program will not allow users to input non-numeric characters. FYI, KeyAscii code for numbers is between 48-57.

Code: Select all

Private Sub Text1_KeyPress(KeyAscii As Integer)
    If KeyAscii < 48 Or KeyAscii > 57 Then
        KeyAscii = 0
        Beep
    End If
End Sub
The problem is users cannot erase or add point to the number he input. Let's change the program.

Code: Select all

Private Sub Text1_KeyPress(KeyAscii As Integer)
    Select Case KeyAscii
        Case Asc(0) To Asc(9)
        Case Asc("-"), Asc("+"), Asc("."), Asc(",")
        Case 8, 13      '8 for backspace and 13 for enter
        Case Else
            KeyAscii = 0
            Beep
    End Select
End Sub
The problem still remain. How if the user add plus sign more than one? It can't be handled by the program above. I will update it later. :)
Post Reply

Return to “Visual Basic Programming”