文本框 - 文本更改事件 Windows C#

4

我遇到了一个问题,需要你的帮助。以下是问题描述:

我在Windows Form C#中有一个txtPenaltyDays

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

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

非常感谢任何建议。


一个更严重的问题。如果你的用户输入了一个字母会发生什么? - Steve
if(txtPenaltyDays.Text=="0") return; - MatthewMartin
是的,史蒂夫,这是真的。这只是我尝试放置的代码的一部分。但在实际代码中,我有按键事件处理所有特殊字符。 - Suzane
5个回答

8
当您发现无效值时,只需禁用事件处理程序,通知用户,然后重新启用事件处理程序即可。
 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。

谢谢Steve...这个可行!感谢大家的建议,但我明白私有变量选项并不是一个好选择,因为这会阻止应用程序级别上的重新触发。 - Suzane
你是否考虑使用NumericUpDown控件?它具有最小值和最大值属性,可以控制允许的值。并且它还能够移除按键处理代码。对于简单的场景来说,这是一个非常有价值的选项。 - Steve

4
您可以使用私有表单字段来防止事件第二次触发:
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 中做会更好?”

这是最佳方法。为了如此小的事情添加和删除事件并不是一个好的模式。 - Steve Coleman

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

1
你可以检查文本框是否没有焦点,然后触发事件: if (!textbox1.Focused) return; 或者绑定和解除绑定事件: textbox1.TextChanged -= textbox1_TextChanged; textbox.Text = "some text"; textbox1.TextChanged += textbox1_TextChanged;

1
你可以使用 Leave 或 LostFocus 事件来代替。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接