2012-12-03 37 views
-2

我想詢問是否有人知道如何限制文本框允許的時間。我正在使用C#Visual Studio 2010.C#期間驗證

我的問題是我需要找到驗證代碼,以確保只允許用戶的文本框Middle Initial的單個句點。如果用戶鍵入另一個句點,則句號不會顯示在文本框中。不需要錯誤消息。示例是僅接受字母的驗證代碼。這裏是我的這個例子代碼:

private void txtFirstName_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      byte num = Convert.ToByte(e.KeyChar); 

     if ((num >= 65 && num <= 90) || (num >= 97 && num <= 122) || (num == 8) || (num == 32)) 
     { 

     } 

     else if (num == 13) 
     { 
      e.Handled = true; 
      SendKeys.Send("{Tab}"); 
     } 
     else 
     { 
      e.Handled = true; 
     } 

    } 

我目前有以下代碼爲我txtboxMI:

private void txtMI_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    byte num = Convert.ToByte(e.KeyChar); 

    if ((num >= 65 && num <= 90) || (num >= 97 && num <= 122) || (num == 8) || (num == 32)) 
    { 

    } 
    else if (num == 13) 
    { 
     e.Handled = true; 
     SendKeys.Send("{Tab}"); 
    } 
    else 
    { 
     e.Handled = true; 
    } 
} 
+0

請添加*你*擁有,而不是你需要完成什麼任務什麼的問題做。附註:不需要感謝你的筆記,簽名,第一次在這裏和類似的,因爲這樣的短語通常不會增加信息的問題。還要注意,「家庭作業」是過時的標籤 - 嘗試對你的問題加以說明,以便它通常是有用的,而不僅限於你的作業。 –

+0

char有很多相關的方法,比如'IsLetter','IsDigit',檢查出來並重新訪問你的代碼 – V4Vendetta

回答

0

試試這個:

var txt = (TextBox)sender; 
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z') || e.KeyChar == 8 || e.KeyChar == 32) { 
} else if (txt.Text.Contains('.') && e.KeyChar == '.') { 
    e.Handled = true; 
} else if (e.KeyChar == '\t') { 
    e.Handled = true; 
    SendKeys.Send("{Tab}"); 
}