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()
You can use the onkeydown Property of the TextBox for limiting its value to numbers only.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With