TextBox - C # TextChanged Windows event
I am stuck with a problem and need inputs. Here is the description -
I have 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 ran into a problem because it works 2 times. Due to setting the text value to 0. My requirement is that it should fire only once and set the value to 0.
Any suggestion is deeply appreciated.
source to share
Just disable the event handler when you encounter an invalid value, notify the user and then re-enable 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;
}
}
Note also that I removed Convert.ToInt16 because it fails if your user types a letter instead of a number and uses Int16.TryParse
source to share
You can use a personal form field to prevent the event from firing a second 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;
}
The best question is, "Should I do this in TextChanged
, or would it be better to do it in Validating
?"
source to share
Try following code
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.TextChanged -= txtPenaltyDays_TextChanged;
txtPenaltyDays.Text = 0;// Re- triggers the TextChanged
txtPenaltyDays.TextChanged += txtPenaltyDays_TextChanged;
}
}
source to share