簡體   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