Avoiding char's in textboxes

yaniv

Well-known member
Joined
Apr 15, 2002
Messages
162
Location
israel
Are there is a simple way to check if the user entered chars in textbox?

I use now a error handling routine, and it seems very complicated.
 
You can just make a string full of them and check to make sure that that char isnt in the String. Simple. :)
Code:
Dim invalidChars As String = "0123456789"
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    If invalidChars.IndexOf(e.KeyChar) >= 0 Then e.Handled = True
End Sub
 
Also, try looking into the Char class. It has a lot of useful methods for evaluating characters that may save you a lot of code. For example, to accept only digits or letters, you can do this:


Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

e.Handled = Not Char.IsLetterOrDigit(e.KeyChar)

End Sub
 
Back
Top