Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have tried everything and I'm still not able to press backspace and space when entering the relevant data (letters) into the textbox.

What I have tried:

If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) < 90 _

And Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then

MessageBox.Show("Please enter letters only")

e.Handled = True

End If
Posted
Updated 21-Dec-17 0:32am
Comments
Makhno Khan Pitafi 1-Nov-23 6:40am    
How to code backspace in vb

Use a Select Case
VB
Select Case Asc(e.KeyChar)
  Case 8, 32, 65 To 90, 97 To 122
     ' allowed
     ' add other blocks as required - eg 48 to 57 to allow numbers

  Case Else  
     MessageBox.Show("Please enter letters only")
End Select

ASCII Tables[^]
 
Share this answer
 
v2
Look at your code:
VB
If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) < 90 _
And Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
If it's below 65, it's below 90.
And what's the precedence of And and Or? Is it evaluated as
(a Or b) And (c Or d)
Or as
a Or (b And c) Or d

Try this:
VB
If Char.IsLetterOrDigit(e.KeyChar) OrElse e.KeyChar = " "c OrElse e.KeyChar = CChar(Keys.Back) Then
        ' All OK.
    Else
        MessageBox.Show("Please enter letters only")
        e.Handled = True
    End If
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900