I'm new to VB .NET and need some help please.
I need help with what code to use for a text box that only can allow numeric keys and the Backspace key. The number can only be 50 or less, otherwise an error message is displayed.
Thank you very much!
Printable View
I'm new to VB .NET and need some help please.
I need help with what code to use for a text box that only can allow numeric keys and the Backspace key. The number can only be 50 or less, otherwise an error message is displayed.
Thank you very much!
The following code will allow only numeric values, backspace key and the tab key to leave the textbox. In your validation routine you can check that the value is less then 50.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim I As Integer = Convert.ToInt32(e.KeyChar)
Select Case I
Case 48 To 57 ' 0-9 (digit)
e.Handled = False
Case 8 ' allow backspace key
e.Handled = False
Case 9 ' allow Tab key
e.Handled = False
Case Else
e.Handled = True
End Select
End Sub
Harold Hoffman
There are also other functions in the framework..
Nevermind, I just saw that the number has to be less than 50. Go with the above code, but keep in mind the System.Char class for stuff like this in the future.Code:Dim key As Integer = Convert.ToInt32(e.KeyChar)
If Not (System.Char.IsNumber(e.KeyChar)) Then
If key <> 8 Then
e.Handled = True
End If
End If
Thanks for the help guys. I'm not quite understanding the code and can't get it to quite work. It blocks all chars except 0-9, but doesn't limit it to 50. The value in the text box is to be multiplied by 80, and displayed in a label as currency. I have that all working except for limiting it to 50. Its also only computing the first digit * 80 until another character is entered. It should be real time. Help! Thanks!
<vbscript>
Private Sub EntNumTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles EnterNumTextBox.KeyPress
Dim I As Integer = Convert.ToInt32(e.KeyChar)
Select Case I
Case 48 To 57 ' 0-9 (digit)
e.Handled = False
Case 8 ' allow backspace key
e.Handled = False
Case 9 ' allow Tab key
e.Handled = False
Case Else
e.Handled = True
End Select
Me.TotalLabel.Text = Val(Me.EnterNumTextBox.Text) * 80
Me.TotalLabel.Text = Format(Me.TotalLabel.Text, "currency")
End Sub
</vbscript>
On the KeyPress event when you are validating for numeric data - throw in a validation of the text already in the textbox with the text you are trying to add.....
e.g.
Let's say you have textbox1="9"
Now, you try to input any other number
(making the number 90-99)
On the keypress event of the textbox, do this....
If Val(textbox1) > 50 then
Messagebox.show ("Value cannot exceed 50, please try again")
textbox1.SelectAll
textbox1.focus()
Endif