I would like to know if there is a proper way for a textbox to accept only numbers.
For example, I want it to "stop" the user from filling it with "abcd1234" and only let him fill with "1234".
I would like to know if there is a proper way for a textbox to accept only numbers.
For example, I want it to "stop" the user from filling it with "abcd1234" and only let him fill with "1234".
I tried following code and worked fine for me. The textbox will allow user to enter numbers only.
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
you can also try this
e.Handled = !(char.IsDigit(e.KeyChar));
You can evaluate the input using the following lines of code:
if (txtNumericBox.Text.All(char.IsDigit))
// Proceed
else
// Show error
If you define this as a string property with getter and setter then you can use like the following:
private string _MyNemericStringr;
public string MyNemericString
{
get { return _MyNemericStringr; }
set {
if (value.All(char.IsDigit))
_MyNemericStringr = value;
else
_MyNemericStringr = "0";
}
}
In the second example, if you assign any non-digit value to the property then it will return the value as "0". otherwise it will process as usual.
you can try this simple code.
private void keypressbarcode(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
it only accept numeric values and Backspace