Quick tip: Filtering input to a TextBox control

Sometimes, it's the little things that take the longest to work out, so I thought I'd start a "Quick tips" series.  Quick tips are intended to be short and solve a very specific issue.

I was talking with Mark Prentice today and we were looking at filtering a TextBox control so that it only accepted numeric characters.  As it works out, this is a very easy thing to do with the .NET Compact Framework.

To filter input that is entered into a TextBox, we need to implement a KeyPress event handler.  When you encounter a character you wish to exclude, set the value of KeyPressEventArgs.Handled to true.  To determine which characters to handle, the Char type has several handy static methods that help determine what type of character was entered into a TextBox.  Since Mark and I were interested in limiting the input to only numeric characters, I will use Char.IsDigit in my example.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e){    // only allow numeric characters    //  all other KeyPress events are cancelled    e.Handled = !Char.IsDigit(e.KeyCode);}

Enjoy!
-- DK

[Edit: fix sentence]

Disclaimer(s): This posting is provided "AS IS" with no warranties, and confers no rights.

Comments

  • Anonymous
    September 30, 2006
    One quick note regarding this method, it won't stop a user pasting non-numeric content, so as always don't forget to validate before the text is actually used.

  • Anonymous
    October 05, 2006
    I was talking with Mark Prentice today and we were looking at filtering a TextBox control so that it

  • Anonymous
    November 07, 2006
    Hi there, I did some various stuff about that. Even a TextBox able to filter numeric content and show text content although the user can't paste or write text in. Prefer the OnTextChanged(EventArgs e) to do your check on the input character. It will avoid text paste stuff or any other unexpected input characters. Thanks for working on the that Mark and David it would be usefull and quicker than trying to do it myself ^^ Reguards

  • Anonymous
    November 08, 2006
    e.KeyCode gave an error. I was able to use e.KeyChar.

  • Anonymous
    November 14, 2006
    i try this code but it can not allow edit as i give backspace after entering digit it can not allow me. try this code, it allso backspace after entering digit. private void txtPhoneno_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if((e.KeyChar < Convert.ToChar("0") || e.KeyChar > Convert.ToChar("9")) && (e.KeyChar != Convert.ToChar("-")) && (e.KeyChar != Convert.ToChar("(")) && (e.KeyChar != Convert.ToChar(")"))) { if (e.KeyChar != Convert.ToChar(Keys.Back) && e.KeyChar != Convert.ToChar(Keys.Delete)) e.Handled = true; } }

  • Anonymous
    June 08, 2009
    PingBack from http://quickdietsite.info/story.php?id=14704