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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With