Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to create an input box for database table names. As such I don't want to allow spaces or special characters but I do want to allow the Underscore, numbers or letters.

I tried putting the following into the keypress event

VB
Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"

If allowedChars.IndexOf(e.KeyChar) = -1 Then
    ' Invalid Character
    e.Handled = True
End If


which was really close but I found that the backspace key wouldn't work which made me nervous about user acceptance ...

So am I on the right track but need more tweaking to get this working or is there another solution that I'm not aware of? (I'm still pretty new to .Net)

Thanks.
Posted

1 solution

Did you tried something like this?

VB
Collapse | Copy Code
Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"

If allowedChars.IndexOf(e.KeyChar) = -1 Or e.KeyChar = Convert.ToChar(Keys.Back) Then
    ' Invalid Character
    e.Handled = True
End If



Cheers!
 
Share this answer
 
Comments
BHort 21-Sep-11 17:04pm    
Just did ... no joy. I thought it was because it would skip the back with the logic you supplied but putting NOT around the 2nd half didn't help ... but I think you might be on the right track ... I'll keep trying ...
BHort 21-Sep-11 17:10pm    
Got it.

The correct If should be:
If allowedChars.IndexOf(e.KeyChar) = -1 And e.KeyChar <> Convert.ToChar(Keys.Back) Then

So the complete solution is to paste:

Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"

If allowedChars.IndexOf(e.KeyChar) = -1 AND e.KeyChar <> Convert.ToChar(Keys.Back) Then
' Invalid Character
e.Handled = True
End If

Into the KeyPress event of a text box.

Hope this helps someone else. I really like it because it means my input testing is done up front.
Mario Majčica 22-Sep-11 1:06am    
Great, sorry but grappa last evening fooled up my logic!

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