Text Box IN VB

How we Limit a Text Box to Accept Only Numbers In VB

In visual basic if want use a text box for input as we now that text boxes are primarily used to receive input from users, or to display text either pre-programmed or from a database source. In Visual Basic it is also possible to limit what type of text input it can accept. or we say that how we Permitted only values in the Textbox.

For this purpose we use a KeyAscii event and simple Instr function ( The InStr function returns the position of the first occurrence of one string within another).

we check our input Ascii value with IF statement using InStr function which checked if this value with in our string which is "0123456789" if the Ascii number is in this string then it its ok if not then this function return 0 and we exit form this IF Statement with 0 KeyAscii .

we explain all this with an example

  1. Select "Standard EXE" from the "New Project" dialog box, then click "Open" button.
  2. Add a text box into the form.
  3. Clear the text caption by erasing the word "Text1" next to the "Text" property at the "Properties" window on the right side of the screen.
  4. Double-click the text box control to display the "Code" window.
  5. This code windows show the CHANGE event.
  6. But we change this event with KeyPress Event
  7. and write the following code:

Private Sub Text1_KeyPress(KeyAscii As Integer)

Const Numbers$ = "0123456789." 'Permitted values in Textbox
If KeyAscii <> 8 Then 'Ascii for BackSpace 8
If InStr(Numbers, Chr(KeyAscii)) = 0 Then 'If false, keypressed is suppressed
KeyAscii = 0
Exit Sub
End If
End If

End Sub

Run the program and try to write Some thing Alphabetic but you can note Text not Permitted the alphabetic but when you type the number 0 to 9 then this number Permitted.

  • Thanks for Reading Share this if You Like this:

View and Download More Tutorials !

Limit a Text Box to Accept Only Numbers In VB 6