2014-02-11 122 views
1

我想根據用戶輸入(按鍵事件)對我的文本框進行驗證。我已將我的文本框的最大長度設置爲3個字符。用戶輸入的第一個字符應該是一個字符(來自a-z),然後這兩個後續字符必須是一個數字。退格是允許的。到目前爲止,我有這個代碼,但不工作,因爲我想..TextBox按鍵事件驗證

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      countChar = this.textBox1.Text; 
      if (String.IsNullOrEmpty(this.textBox1.Text)) 
      { 
       e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back); 
      } 
      else if (countChar.Length == 1) 
      { 
       e.Handled = e.KeyChar == (char)Keys.Back; 
      } 
      else if (countChar.Length == 2 || countChar.Length == 3) 
      { 
       e.Handled = e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == (char)8; 
      } 
    } 

有什麼建議嗎?

+0

你介意詳細闡述了 「不工作」?這並沒有真正告訴我們。編譯錯誤?運行時異常?意外的行爲?如果行爲出乎意料,解決這個問題的最好方法是逐步完成代碼。我們不能那樣做。 – tnw

+0

此外,它聽起來像你想介意嘗試一些正則表達式來驗證文本框的內容。可能比嘗試驗證每一個按鍵更容易。 – tnw

+0

哦,對不起,我只是想說,它有一些意想不到的行爲。當我在文本框中輸入第一個字符時,它會接受它是否是字符而不是數字。但是,當我在文本框中輸入第二個字符時,它不接受它是字符還是數字。我試過了代碼,仍然感到困惑。對不起,我的英語不好。 – user3233787

回答

0

這應該工作

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     countChar = this.textBox1.Text; 

     if (String.IsNullOrEmpty(this.textBox1.Text)) 
     { 
      e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back); 
     } 
     else if (countChar.Length == 1 || countChar.Length == 2) 
     { 
      e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back); 
     } 
     else if (countChar.Length == 3) 
     { 
      e.Handled = e.KeyChar != (char)Keys.Back; 
     } 
     else 
     { 
      e.Handled = true; 
     } 
    } 
0
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     countChar = this.textBox1.Text; 
     if (String.IsNullOrEmpty(this.textBox1.Text)) 
     { 
      e.Handled = (char.IsLetter(e.KeyChar); 
     } 
     else if (countChar.Length == 1 || countChar.Length == 2) 
     { 
      e.Handled = e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == (char)8; 
     } 
     e.Handled=false; 
    } 
+0

可能要解釋此代碼... – tnw

+0

第一個字符的文本框是空的。所以首先如果你可以檢查它。爲2個下一個字符您的文本框長度是1或2.否則輸入字符不正確 –

+0

對不起,它不工作,因爲我想。 – user3233787