vb.net make a text box enter only numbers
The text box control textbox is added first to change the value of the property IMEMode to disable so that you cannot use the Chinese input method in the text box. Then add the following code to the KeyPress event for the text box
Private Sub Textbox1_keypress (ByVal sender As Object, ByVal e As System.windows.forms.keypresseventargs) Handles TextBox1 . keypress
If Char.isdigit (E.keychar) or E.keychar = Chr (8) Then
E.handled = False
Else
E.handled = True
End If
End Sub
If the text needs to enter a decimal, you can enter the decimal point "." and the decimal point can only be entered once, at this time, the above function could be changed to the following format:
Private Sub Textbox1_keypress (ByVal sender As Object, ByVal e As System.windows.forms.keypresseventargs) Handles TextBox1 . keypress
If Char.isdigit (E.keychar) or E.keychar = Chr (8) or E.keychar = "." Then
If E.keychar = "." And InStr (TextBox1.Text, ".") >0 Then
E.handled = True
Else
E.handled = False
End If
Else
E.handled = True
End If
End Sub
If the text needs to enter a negative number, you can enter the minus sign "-", and only the first character entered in the text box, you can change the above function to the following format:
Private Sub Textbox1_keypress (ByVal sender As Object, ByVal e As System.windows.forms.keypresseventargs) Handles TextBox1 . keypress
If Char.isdigit (E.keychar) or E.keychar = "." Or E.keychar = Chr (8) Then
If E.keychar = "." And InStr (TextBox1.Text, ".") >0 Then
E.handled = True
Else
E.handled = False
End If
ElseIf E.keychar = "-" and TextBox1.Text = "" Then
E.handled = False
Else
E.handled = True
End If
End Sub
The text box can then be used to enter positive or negative integers and decimals.
When you have more than one text box that requires an input limit, you can add the KeyPress event for multiple text boxes after the above code handles, separated by commas, for example
Private Sub Textbox1_keypress (ByVal sender As Object, ByVal e As System.windows.forms.keypresseventargs) handles T Extbox1.keypress,textbox2.keypress,textbox3.keypress
For the function to judge the content of the text box, the code should be modified so that it can handle multiple text boxes at the same time, that is, change the TextBox1.Text in the latter two sections to CType (sender, TextBox). Text, so that you can For example, the code that can enter a minus sign can be changed to:
Private Sub Textbox1_keypress (ByVal sender As Object, ByVal e As System.windows.forms.keypresseventargs) Handles TextBox1 . keypress,textbox2.keypress,textbox3.keypress
If Char.isdigit (E.keychar) or E.keychar = "." Or E.keychar = Chr (8) Then
If E.keychar = "." And InStr (CType (Sender, TextBox). Text, ".") >0 Then
E.handled = True
Else
E.handled = False
End If
ElseIf E.keychar = "-" and CType (sender, textbox). Text = "" Then
E.handled = False
Else
E.handled = True
End If
End Sub