Blog : Textbox to accept only characters in vb.net

textbox to accept only characters in vb.net


 creating a simple application in Vb.net where i need to do validations So I want a name textbox to accept only characters from a-z and A-Z

For this i wrote 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 sum how it is not allowing me to enter character.... when i try to enter any character it does nothing

can sumbody help me with this plssss

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.