Link to home
Start Free TrialLog in
Avatar of csharp_learner
csharp_learnerFlag for Singapore

asked on

Text input limitation C#

Hi I have a textbox1 and a button event.
I want to limit the input of the text box to only accecpt letters or numbers and not accecpt anything like ".,!@#$%" for the 1st character in the textbox.

Is that possible?Thanks for the help.
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Of course that's possible, e.g.:


Use Char.IsLetterOrDigit(char), you need to use the KeyPress event to get the characters and cancel (Handled) the event.

Do you need further help?
ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of csharp_learner

ASKER

Thanks for the prompt reply.
Can I use this Char.IsLetterOrDigit(char) methold to check for the 1st letter in the texbox when my button click event activates?
And if I use Char.IsLetterOrDigit(char) do I have to input every ".,./'!@#$$..." under "char" I want to filter?
Well if u want to check on click of button, you might also consider using regular expressions, if it is possible.
Hi informaniac can you elaborate what you mean by using regular expressions?
Not sure if I understand your question: "And if I use Char.IsLetterOrDigit(char) do I have to input every ".,./'!@#$$..." under "char" I want to filter? ".

Did you try my code? If not - try. You won't be able to enter any chars except digits and letter. That's simple.

informaniac has a point. What happens if you enter text by using ctrl-V? The approach I showed will not work. In other words you need to check entire block of inserted text and chack for invalid characters.
In this case you need to use what's called regular expressions, e.g.

http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

Not very easy unfortunately if you are not familiar to the concept.
OK, about Char.IsLetterOrDigit(char):

char comes from the event argument, it corresponds to a key pressed.
Yes, anarki_jimbel it works but is there a way to enable the "Backspace" key?
It's possible:

'\b' - denotes backspace.
Or you may use a number 8
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsLetterOrDigit(e.KeyChar) && e.KeyChar!= '\b')//
            {
                e.Handled = true;
            }
        }

Open in new window