I looked all over for something to accomplish what should be a very basic task in C#: Allowing only Numeric entry in a text box. Oddly for such an otherwise fantastic development setup, Microsoft provides only the MaskedEdit control, which insists on using a placeholder character (among other limitations). Any other validation has to be manually implemented.
Most of the solutions I found online looked confusing and did way more than I wanted. I found bits and pieces and cobbled together the following function:
public bool IsIntegerEntry(int intKey)
{
//Allow only numeric characters (48-58)
// and control characters (1-31) for copy/backspace/etc.
return (((intKey >= 48) && (intKey <= 58)) || (intKey < 32))
}
Call it as follows from the KeyPress function of the appropriate TextBox: e.Handled = !IsIntegerEntry(e.KeyChar);
I'm sure there are plenty of gotchas (I'm utterly n00b-tastic when it comes to C#), but it doesn't need to be bulletproof for simple data entry purposes. If they manage to squeeze in a non-integer character in there somewhere, either later validation or database will throw it back regardless.
If you need to validate negative or decimal numbers, be sure to tack an additional "|| (intKey == x)" for the additional ASCII codes at the end of the if statement (45 and 46, respectively). Happy coding!
*This was an age of innocence and happiness.
Posted by: christian louboutin | November 07, 2010 at 05:17 PM
Nothing down, nothing up.
Posted by: ugg store | November 11, 2010 at 01:15 AM
GOOD LUCK!
Posted by: taobao buy | November 11, 2010 at 07:09 PM