How to restrict a Textbox to only accept numbers in C#

Posted by: Johnnyboy in C sharp on

If you've ever wanted to restrict a texbox control to accept only numbers and not even allow the user to type characters this is how to do it.  Note that this code also allows the user to type non alpha characters like backspace.

private void txtNumber_KeyDown(object sender, KeyEventArgs e)
{
     if ((e.KeyValue > 0 && e.KeyValue < 31) || (e.KeyValue > 47 && e.KeyValue < 58))
     {
         //Allow all numbers to be printed
     }
     else
     {
         e.SuppressKeyPress = true;
     }
}

Thanks Jordan for this very helpful bit of information!


Trackback(0)
Comments (0)add comment

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

busy