Click here to Skip to main content
15,894,907 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void txtPrinterNumber_KeyPress(object sender, KeyPressEventArgs e)
       {
           if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
               e.Handled = true;

       }
Posted
Comments
BillWoodruff 17-Feb-15 5:55am    
There's numbers, and then there's ... numbers. Filtering for integers is one thing, filtering for Doubles is another. How many decimal-points/period/dots do you allow if you're filtering for a Double ... and where; what if the current culture defines a comma as a valid separator in a number as in 100,000.9345 ?

What did you have in mind ? Specifics, please.

C#
private void txtPrinterNumber_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
            e.Handled = true;
    }

    // only allow one decimal point
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }
}
 
Share this answer
 
v2
It can be done - it's not complex, it's just annoying, because you have to handle it in a number of places to prevent paste adding alpha as well.

The better solution is to use a NumericUpDown control, which does it all for you.

If you are going to do it manually, consider looking at the TextChanged event and using Regex.Replace instead of IsMatch - but don't forget the cursor position may need correcting.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900