Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBox - TextChanged event Windows C#

Tags:

c#

winforms

I am stuck into a problem and need inputs. Here is the description -

I have a txtPenaltyDays in windows form C#

private void txtPenaltyDays_TextChanged(object sender, EventArgs e)
{
  if(Convert.ToInt16(txtPenaltyDays.Text) > 5)
  {
    MessageBox.Show("The maximum amount in text box cant be more than 5"); 
    txtPenaltyDays.Text = 0;// Re- triggers the TextChanged 
  }
}

But I am running into problem because this fires 2 times. Because of setting the text value to 0. My requirement is that it should fire only one time and set the value to 0.

Any suggestion is deeply appreciated.

like image 218
Suzane Avatar asked Dec 06 '22 00:12

Suzane


2 Answers

Just disable the event handler when you discover the invalid value, inform the user and then reenable the event handler

 private void txtPenaltyDays_TextChanged(object sender, EventArgs e)
 {
   short num;
   if(Int16.TryParse(txtPenaltyDays.Text, out num))
   {
       if(num > 5)
       {
           txtPenaltyDays.TextChanged -= txtPenaltyDays_TextChanged;
           MessageBox.Show("The maximum amount in text box cant be more than 5"); 
           txtPenaltyDays.Text = "0";//
           txtPenaltyDays.TextChanged += txtPenaltyDays_TextChanged;
       }
   }
   else
   {
      txtPenaltyDays.TextChanged -= txtPenaltyDays_TextChanged;
      MessageBox.Show("Typed an invalid character- Only numbers allowed"); 
      txtPenaltyDays.Text = "0";
      txtPenaltyDays.TextChanged += txtPenaltyDays_TextChanged;
   }
 }

Notice also that I have removed the Convert.ToInt16 because it fails if your user types a letter instead of a number and used Int16.TryParse

like image 195
Steve Avatar answered Dec 10 '22 13:12

Steve


You can use a private form field to keep the event from firing the 2nd time:

private bool _IgnoreEvent = false;

private void txtPenaltyDays_TextChanged(object sender, EventArgs e)
 {
   if (_IgnoreEvent) { return;}
   if(Convert.ToInt16(txtPenaltyDays.Text)>5)
    MessageBox.Show("The maximum amount in text box cant be more than 5"); 
    _IgnoreEvent = true;
    txtPenaltyDays.Text = 0;// Re- triggers the TextChanged, but will be ignored 
    _IgnoreEvent = false;
 }

A better question would be, "should I do this in TextChanged, or would it be better to do it in Validating?"

like image 20
C-Pound Guru Avatar answered Dec 10 '22 12:12

C-Pound Guru