Allowing only letters and space key in text box

donrecardo

Member
Joined
Sep 24, 2009
Messages
14
Programming Experience
Beginner
Hi
Still struggling with my vb.net 2003 at college ,
Lately things have gone quite well but I just came across a new problem

I have a textbox and I need to restrict entry to only the letters A-Z , a-z and the space key

I know I need to use something like
If (Microsoft.VisualBasic.Asc(e.KeyChar) < 65) _
Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 90)
etc
with an e.handled at the end


I found the above code while searching online but cant quite get it , can some one poiunt me in the right direction

Regards Don
 
I prefer to use Select Case:
VB.NET:
[FONT="Courier New"]Select Case Convert.ToInt32(e.KeyChar)
      Case 48 To 57      'numbers
      Case 65 To 122     'letters
      Case Keys.Back     'just in case they make a mistake
      Case Keys.Enter    'clicks a button if you want
        btn.PerformClick()
      Case Keys.Space
      Case Else
        e.Handled = True
End Select[/FONT]
Unicode Character:cool:
 
I prefer using the KeyPress event:
VB.NET:
e.Handled = Not (char.IsLetter(e.KeyChar) OrElse e.KeyChar = Keys.Space)
Of course you'll still want to use the Validate event to verify the contents before proceeding with the data.
 
Back
Top