Search code examples
vb.netasciikeypress

Get a textbox to accept only characters in vb.net


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?


Solution

  • 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.