Sometimes we need to put some restrictions to Textbox’s text so that only specific type of data can be inputted. Today we’re going to discuss a way so that only Numerics can be inputted. For example you have two text boxes and the function of your software is to add the numbers present in both Text boxes. Then user must enter numerics in both text boxes. If by mistake any alphabet or symbol is input, program will give exception. To avoid such situation, we apply restrictions to the text boxes so that nothing else can be inputted in except numerical values.
For this, we have to use the KeyPress event of the text box. Then we’ll have to use the following code:
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
e.KeyChar will tell the character which is pressed. “<> 8 = Less than or more than 8” allows backspace key to be pressed. In ASCII, 48 indicates 0 and 57 indicates 9. Inbetween 48 and 57, there are numbers. From Line 2 to Line 4, VB.NET check if the entered character is number or not. If it is number, it is allowed to be printed.
Join Us On Facebook and Twitter and you can subscribe via email too