TextBox - TextChanged事件Windows C#

时间:2014-10-09 17:28:30

标签: c# winforms

我陷入困境并需要输入。这是描述 -

我在Windows窗体中有一个txtPenaltyDays 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 
  }
}

但我遇到了问题,因为这会引发2次。因为将文本值设置为0。 我的要求是它应该只触发一次并将值设置为0.

任何建议都深表赞赏。

5 个答案:

答案 0 :(得分:3)

您可以使用私有表单字段来阻止事件第二次触发:

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;
 }

更好的问题是,“我应该在TextChanged中执行此操作,还是最好在Validating中执行此操作?”

答案 1 :(得分:3)

发现无效值时,只需禁用事件处理程序,通知用户然后重新启用事件处理程序

 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;
   }
 }

另请注意,我已删除Convert.ToInt16,因为如果您的用户键入字母而不是数字并使用Int16.TryParse

,则会失败

答案 2 :(得分:3)

尝试以下代码

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;
   }
}

答案 3 :(得分:1)

您可以使用事件Leave或LostFocus代替。

答案 4 :(得分:1)

您可以检查文本框是否未聚焦,然后触发事件:

String

或绑定和取消绑定事件:

if (!textbox1.Focused) return;