Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.net Need Text Box to Only Accept Numbers

I'm fairly new to VB.net (self taught) and was just wondering if someone out there could help me out with some code. I'm not trying to do anything too involved, just have a TextBox that accepts a numeric value from 1 to 10. I don't want it to accept a string or any number above 10. If someone types a word or character an error message will appear, telling him to enter a valid number. This is what I have; obviously it's not great as I am having problems. Thanks again to anyone who can help.

 If TxtBox.Text > 10 Then         MessageBox.Show("Please Enter a Number from 1 to 10")         TxtBox.Focus()     ElseIf TxtBox.Text < 10 Then         MessageBox.Show("Thank You, your rating was " & TxtBox.Text)         Total = Total + 1     ElseIf IsNumeric(TxtBox.Text) Then         MessageBox.Show("Thank you, your rating was " & ValueTxtBox.Text)     End If      ValueTxtBox.Clear()     ValueTxtBox.Focus() 
like image 376
Rico Jackson Avatar asked Apr 02 '12 01:04

Rico Jackson


People also ask

How do I restrict a textbox to accept only numbers in VB net?

You can use the onkeydown Property of the TextBox for limiting its value to numbers only.

How do I allow only numbers in a text box?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.


1 Answers

You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyChar represents the key that's pressed. And the the built-in function Asc() converts it into its Ascii integer.

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress      '97 - 122 = Ascii codes for simple letters     '65 - 90  = Ascii codes for capital letters     '48 - 57  = Ascii codes for numbers      If Asc(e.KeyChar) <> 8 Then         If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then             e.Handled = True         End If     End If  End Sub 
like image 63
Isuru Avatar answered Sep 21 '22 01:09

Isuru