Get a textbox to accept only characters in vb.net

59,223

Alternatively, you can do something like this,

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
                              Handles txtName.KeyPress

    If Not (Asc(e.KeyChar) = 8) Then
        Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz"
        If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
            e.KeyChar = ChrW(0)
            e.Handled = True
        End If
    End If

End Sub

or if you still want the ASCII way, try this,

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress

    If Not (Asc(e.KeyChar) = 8) Then
        If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90)) Then
            e.KeyChar = ChrW(0)
            e.Handled = True
        End If
    End If

End Sub

both will behave the same.

Share:
59,223

Related videos on Youtube

EqEdi
Author by

EqEdi

Updated on March 03, 2020

Comments

  • EqEdi
    EqEdi over 4 years

    I'm creating a simple application in Vb.net where I need to perform certain validations. So I want a name textbox to accept only characters from a-z and A-Z for example.

    For this I wrote the following code:

       Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) > 65 Or Asc(e.KeyChar) < 90 Or Asc(e.KeyChar) > 96 Or Asc(e.KeyChar) < 122 Then
                e.Handled = True
            End If
        End If
    End Sub
    

    But somehow it is not allowing me to enter characters. When I try to enter any character it does nothing.

    What causes this problem and how can I resolve it?

  • EqEdi
    EqEdi almost 12 years
    But even the code wich i wrote shd work .... do u think there issum prob wid the code ??
  • John Woo
    John Woo almost 12 years
    @EqEdi your code will not work because your conditions are messed up, causing the compiler to confuse :D
  • fedeteka
    fedeteka over 7 years
    @JohnWoo Nice solution. Adapted and linked on stackoverflow.com/questions/41151574/…
  • Nathan Tuggy
    Nathan Tuggy about 7 years
    Generally, don't put code in comments. Edit your answer instead, and make sure you use code block formatting for readability.
  • sandwhale
    sandwhale over 2 years
    if this work with numeric ?