Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to disallow zero in textbox using char.IsDigit

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 !";
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading