Home > Software design >  Why the result of IsDigit is not as intended
Why the result of IsDigit is not as intended

Time:02-03

In the below code if I enter numbers then it flashes error message instead it should flash in case of alphabets. I want to allow only numbers.

Also if I enter number and then any alphabet for e.g. 33er then the error msg is displayed and unless and untill I do not remove whole text the msg flashes, I have remove whole text and then I have enter numbers.

if (e.Handled != char.IsDigit(e.KeyChar))
{
   errorProvider1.SetError(label1, "Allow Only Numeric Values !");
   label1.Text = "Allow Only Numeric Values !";
}
else
{
   errorProvider1.SetError(label1, "");
   label1.Text = "";
}

CodePudding user response:

I suggest not checking e.Handled but set it to true when required

if (char.IsDigit(e.KeyChar)) {
  // Expected input, clear error messages
  label1.Text = "";
}
else {
  // Do not accept user input
  e.Handled = true;

  // Show error messages
  label1.Text = "Allow Only Numeric Values !";
}

// Let's not repeat ourselves
errorProvider1.SetError(label1, label1.Text);
  •  Tags:  
  • c#
  • Related