繁体   English   中英

TextBox - TextChanged事件Windows C#

[英]TextBox - TextChanged event Windows C#

我陷入困境,需要投入。 这是描述 -

我在Windows窗体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 
  }
}

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

任何建议都深表感谢。

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

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做得更好?”

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

 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,则会失败

请尝试以下代码

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

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

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

if (!textbox1.Focused) return;

或绑定和解除绑定事件:

textbox1.TextChanged -= textbox1_TextChanged; textbox.Text = "some text"; textbox1.TextChanged += textbox1_TextChanged;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM