Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only numbers and negative values

Tags:

c#

.net

winforms

I have a textbox which needs only accept numbers (can be decimal values) and negative values.

Currently I have something like this in KeyPress event

   if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;                
    }

What else I should do in order to allow negative values?

Thanks

like image 374
huMpty duMpty Avatar asked Oct 31 '12 12:10

huMpty duMpty


1 Answers

if (!char.IsControl(e.KeyChar) && (!char.IsDigit(e.KeyChar)) 
        && (e.KeyChar != '.')  && (e.KeyChar != '-'))
    e.Handled = true;

// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
    e.Handled = true;

// only allow minus sign at the beginning
if (e.KeyChar == '-' && (sender as TextBox).Text.Length > 0)
    e.Handled = true;

As L.B correctly mentioned in the comments this won't allow some advanced notations like 3E-2, but for simple numbers it will do the trick.

like image 95
Dennis Traub Avatar answered Sep 22 '22 00:09

Dennis Traub