C# 文字框限制大全
阿新 • • 發佈:2019-01-05
雙擊事件中的KeyPress事件
1.只能輸入數字和字母,退格鍵:
//文字框限制只能輸入數字和字母,退格鍵: private void textBox_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; } }
2.只能輸入數字
#region//只能輸入數字 if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46) e.Handled = true; //小數點的處理。 if ((int)e.KeyChar == 46) //小數點 { if (txtPassWord.Text.Length <= 0) e.Handled = true; //小數點不能在第一位 else { float f; float oldf; bool b1 = false, b2 = false; b1 = float.TryParse(txtPassWord.Text, out oldf); b2 = float.TryParse(txtPassWord.Text + e.KeyChar.ToString(), out f); if (b2 == false) { if (b1 == true) e.Handled = true; else e.Handled = false; } } } #endregion
3.只能輸入漢字
private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)
{
//只能輸入漢字
Regex rg = new Regex("^[\u4e00-\u9fa5]$");
if (!rg.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}