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.