TextBox - TextChanged 事件 Windows C# [英] TextBox - TextChanged event Windows C#

查看:42
本文介绍了TextBox - TextChanged 事件 Windows C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am stuck into a problem and need inputs. Here is the description -

我在 Windows 窗体 C# 中有一个 txtPenaltyDays

I have a 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 
  }
}

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

But I am running into problem because this fires 2 times. Because of setting the text value to 0. My requirement is that it should fire only one time and set the value to 0.

非常感谢任何建议.

推荐答案

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

Just disable the event handler when you discover the invalid value, inform the user and then reenable 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;
   }
 }

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

Notice also that I have removed the Convert.ToInt16 because it fails if your user types a letter instead of a number and used Int16.TryParse

这篇关于TextBox - TextChanged 事件 Windows C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆