TextBox - TextChanged 事件 Windows C#

2023-11-30

我遇到了一个问题,需要输入。这是描述 -

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

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

任何建议都深表赞赏。


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

 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,它将失败

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TextBox - TextChanged 事件 Windows C# 的相关文章

随机推荐