C#機房重構之常用限定條件彙總
阿新 • • 發佈:2018-12-12
限制只能輸入數字
//限制只能輸入數字------------------------------------------------------ private void txtUserID_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar != '\b' && !Char.IsDigit(e.KeyChar)) { e.Handled = true; MessageBox.Show("請輸入數字,並確保在11位以內!"); } }
限制只能輸入字母和數字
//限制密碼只能輸入字母或者數字 private void txtPassword_KeyPress(object sender, KeyPressEventArgs e) { if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == 8)) { e.Handled = false; } else { e.Handled = true; MessageBox.Show("密碼只能是字母或者數字"); } }
限制只能輸入漢字
//新增名稱空間 using System.Text.RegularExpressions; //限制只能輸入漢字 private void txtSName_KeyPress(object sender, KeyPressEventArgs e) { Regex rg = new Regex("^[\u4e00-\u9fa5\b]$"); //\b是退格鍵 if (!rg.IsMatch(e.KeyChar.ToString())) { e.Handled = true; MessageBox.Show("您只能輸入漢字!"); } }