0

I am using C#, Visual Studio 2010, Windows Form Application, and working with a textbox.

For this textbox, I don't want the user to be able to press any key aside from numbers, backspace, and letters (lower and upper case). Any other characters (such as @#$%^) will result in a beep and reject the keypress.

What would be the code to check for those range of keys?

Thank you!

user3215251
  • 239
  • 1
  • 16
  • You know how to handle key events? You know how to compare characters? What have you tried so far? Have you done any research yet? – marsze Jan 20 '14 at 13:29

1 Answers1

1
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!(Char.IsLetter(e.KeyChar) || Char.IsDigit(e.KeyChar) || Char.IsControl (e.KeyChar))){
        e.Handled = true;
        Console.Beep(); 
    }
}

But, like MusiGenesis said in this question: Allow only alphanumeric in textbox

Handling the KeyDown or KeyPress events is not enough. A user can still copy-and-paste invalid text into the textbox.

A somewhat better way is to handle the TextChanged event, and strip out any offending characters there. This is a bit more complicated, as you have to keep track of the caret position and re-set it to the appropriate spot after changing the box's Text property.

Depending on your application's needs, I would just let the user type in whatever they want, and then flag the textbox (turn the text red or something) when the user tries to submit.

Community
  • 1
  • 1
Zzyrk
  • 907
  • 8
  • 16