Check textbox in vb.net
You can check the text string, i.e. textbox1.text, to make sure it has nothing but alphabet characters in the .Leave event. This will throw an error if the user types the following control, for example. You can do this using a regular expression (import System.Text.RegularExpressions for this example), or you can check the text "manually".
Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
If Not Regex.Match(TextBox1.Text, "^[a-z]*$", RegexOptions.IgnoreCase).Success Then
MsgBox("Please enter alpha text only.")
TextBox1.Focus()
End If
End Sub
If you want to stop the user as soon as the non-alpha key is pressed, you can use the TextChanged event instead of the .Leave event.
source to share
If it is a standard text box in a WinForms application, you can test each typed character by handling the event KeyPressed
and getting the following code in the event handler:
e.Handled = Not Char.IsLetter(e.KeyChar)
The user can still use the mouse to paste something there, although you may need to handle this.
Another option is to handle the event Validating
and if the textbox contains any non-alphabetic characters you set e.Cancel
to true.
source to share