INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Visual Basic (Microsoft) Versions 5/6 FAQ

Processing User Input

How do I make sure that only numbers are entered into a text box? by MikeLacey
Posted: 31 May 00

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.



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


Back to Visual Basic (Microsoft) Versions 5/6 FAQ Index
Back to Visual Basic (Microsoft) Versions 5/6 Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close