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.
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
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
?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With