I have the below code wherein it works for only numbers and backspace but I want to also have that no zeros are allowed, but it is not working
private void TxtNumber4_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char.IsDigit(e.KeyChar)) || (char.IsControl(e.KeyChar)) || (int)e.KeyChar == 0)
{
errorProvider1.SetError(LblNum2, "");
LblNum2.Text = "";
}
else
{
e.Handled = true;
errorProvider1.SetError(LblNum2, "Allow Only Numeric Values !");
LblNum2.Text = "Allow Only Numeric Values !";
}
}
>Solution :
Let’s start from the other end, i.e. what we allow: '1'..'9' (note they are chars, say '1' is not int 1) and all the control chars:
private void TxtNumber4_KeyPress(object sender, KeyPressEventArgs e) {
// If e.KeyChar is a control character
// or it some char from '1'..'9' we allow it
if (char.IsControl(e.KeyChar) || e.KeyChar >= '1' && e.KeyChar <= '9') {
errorProvider1.SetError(LblNum2, "");
LblNum2.Text = "";
}
else {
e.Handled = true;
errorProvider1.SetError(LblNum2, "Allow Only Numeric Values !");
LblNum2.Text = "Allow Only Numeric Values !";
}
}