2014-10-09 57 views
3

我陷入一個問題,需要輸入。這裏是描述 -TextBox - TextChanged事件Windows C#

我在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 
    } 
} 

txtPenaltyDays但是我遇到了問題,因爲這個火災的2倍。由於設置文本值爲0. 我的要求是,它應該只觸發一次並將值設置爲0.

任何建議深表讚賞。

+0

一個更嚴重的問題。如果你的用戶輸入一個字母會發生什麼? – Steve 2014-10-09 17:31:39

+0

if(txtPenaltyDays.Text ==「0」)return; – MatthewMartin 2014-10-09 17:32:42

+0

是的,它是真實的。這只是我試圖放置的代碼的一部分。但在實際的代碼中,我有按鍵事件處理所有特殊字符 – Suzane 2014-10-09 17:33:27

回答

3

只是禁用事件處理程序,當你發現無效值,通知用戶,然後重新啓用該事件處理程序

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

+0

謝謝史蒂夫......這工作!感謝球員的輸入,但我明白,私人變量選項不是一個好的,因爲這將防止應用程序級別的重新觸發。 – Suzane 2014-10-09 17:45:37

+0

您是否考慮過使用NumericUpDown控件?它具有控制允許值的最小和最大屬性。它刪除了按鍵處理代碼。對於簡單的場景,這是一個有價值的選擇 – Steve 2014-10-09 17:48:53

3

您可以使用一個專用表單域燒製而成的第二次保持事件:

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?「

+0

這是最好的方法。添加和刪​​除事件這麼小是不是一個好的模式 – 2014-10-09 20:45:00

1

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

3

嘗試下面的代碼

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

,您可檢查文本框不集中的N個加熱事件:

if (!textbox1.Focused) return;

或綁定和取消綁定事件:

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

相關問題