2016-09-12 30 views
-1

我正在爲類創建一個Windows窗體程序,我試圖限制從1-1000到「權重」文本框的輸入。我得到了用戶輸入來解析到一個double,但是由於某種原因,我創建的錯誤消息不會按照預期在合適的時間彈出。 (如果我進入過5位數字的錯誤訊息,只會彈出...所以我可以輸入2222或10000沒有錯誤)Windows窗體。將用戶輸入限制在一定範圍內

private void Weight_KeyPress(object sender, KeyPressEventArgs e) 
{ 
var sourceValue = Weight.Text; 
double doubleValue; 
if (double.TryParse(sourceValue, out doubleValue)) 
{ 
    if (doubleValue > 1000) 
    { 
     MessageBox.Show("Cannot be greater than 1000"); 
    } 
} 
} 
+1

爲什麼你不使用[的NumericUpDown(https://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown(V = vs.110)的.aspx)控制這項任務? – Steve

+0

感謝您的回覆。我的老師要求我使用用戶輸入。 –

+0

您能否解釋一下您在哪種情況下調用此代碼? – Steve

回答

0

,而不是使用按鍵響應,因爲如果你使用的按鍵,你應該使用TextChanged事件 新的字符不是控制文本的一部分。

private void inputTextBox_TextChanged(object sender, EventArgs e) 
     { 
      var inputTextBox = sender as TextBox; 
      var sourceValue = inputTextBox.Text; 
      double doubleValue; 
      if (double.TryParse(sourceValue, out doubleValue)) 
      { 
       if (doubleValue > 1000) 
       { 
        MessageBox.Show("Cannot be greater than 1000"); 
       } 
      } 
     } 
相關問題