Click here to Skip to main content
16,017,312 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a textbox that is handled by a keypress. I want the textbox must accept only alphabet, numbers and allowing him to press the backspace.

how can i do it ?

but the backspace does not work

thanks for any fast reply

THANKS
Posted
Comments
Andreas Gieriet 12-May-13 11:39am    
What do you have coded so far?
What do you mean by "does not work"?
Your title does not make any sense to me...
Please rephrase your title, show your code that causes problems, and take the time to explain your problem in proper and full sentences.
Thanks
Andi

1 solution

I would start by handling the TextChanged event for the TextBox - ignore the key events, as they will still allow unwanted data in via Paste (form keyboard or mouse).

In the TextChanged event, replace all unwanted characters with empty strings.
C#
private void MyTextBox_TextChanged(object sender, EventArgs e)
    {
    TextBox tb = sender as TextBox;
    if (tb != null)
        {
        string original = tb.Text;
        string revised = Regex.Replace(original, "[^\\w]", "");
        if (original != revised)
            {
            int cursor = tb.SelectionStart;
            tb.Text = revised;
            tb.SelectionStart = cursor;
            }
        }
    }
 
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