Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I make sure that only numbers are entered into a text box?

Processing User Input

How do I make sure that only numbers are entered into a text box?

by  MikeLacey  Posted    (Edited  )
Each time the user types a character into a text box the KeyPress event is triggered. The Ascii value of the typed character is passed as the parameter KeyAscii. The keystroke may be rejected by setting KeyAscii to zero.

There's an example function below that only accepts numbers, the '.' character (for a decimal point) and the backspace character to allow the user to edit.

To test the sample code below:

1 Start a new VB project
2 Put a text box named Text1 (the default name) on the form

3 Double click on the form and copy the code below into the code window.

4 Press F5 to run the sample application. You should not be able to enter any characters other than 0123456789. into the text box.

[tt]

Option Explicit

Function OnlyNumericKeys(KeyAscii As Integer) As Integer

Select Case KeyAscii
Case 8, 46, 48 To 57 ' allow backspace, '.' and digits
Case Else: KeyAscii = 0 ' reject everything else
End Select
OnlyNumericKeys = KeyAscii

End Function

Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = OnlyNumericKeys(KeyAscii)
End Sub
[/tt]

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top