加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

TextBox – TextChanged事件Windows C#

发布时间:2020-12-14 05:45:39 所属栏目:Windows 来源:网络整理
导读:我陷入困境,需要投入.这是描述 – 我在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 b
我陷入困境,需要投入.这是描述 –

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读