代碼如下:
調用TextBox的KeyPress事件
private void txtUserId_KeyPress(object sender, KeyPressEventArgs e)
{
//如果輸入的不是數字鍵,也不是回車鍵、Backspace鍵,則取消該輸入
if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar!=(char)13 && e.KeyChar!=(char)8)
{
e.Handled = true;
}
}

注意事項
C#文本框輸入限制
//只能輸入數字和小數點和退格鍵
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
{
e.Handled = true;
}
}
//只能輸入數字和退格鍵
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
{
e.Handled = true;
}
}
//限制輸入只能為數字
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (Char)8)
{
e.Handled = true;
}
}
//限制輸入不能為中文和全角
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
int chfrom = Convert.ToInt32("4e00", 16);//范圍(0x4e00~0x9fa5)轉換成int(chfrom~chend)
int chend = Convert.ToInt32("9fa5", 16);
if (e.KeyChar >= (Char)chfrom && e.KeyChar <= (Char)chend)
{
e.Handled = true;
}
if (e.KeyChar >= (Char)65281 & (int)e.KeyChar <= (Char)65374)
{
e.Handled = true;
}
}
//限制輸入只能輸入數字和字母,退格鍵
private void txt_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;
}
}
【C# 文本框只能輸入數字】
猜你喜歡
- C4D只能整體等比例縮放,不能單方向縮放怎么辦
- cad命令輸入框沒了 cad找回命令框的具體方法
- chm怎么轉換成文本 看完就知道了
- 電腦上輸入法不見了怎么辦 只能輸英文 電腦輸入法只能打英文怎么辦?
- qq說說長圖一次只能發一張嘛
- 眼鏡框縫隙有臟物怎么清洗
- Python中的Django框架有哪些優缺點?Django框架優缺點總結
- ppt如何給文本添加長陰影效果?ppt立體字效設計教程
- 1864年“幼天王”洪天貴福被凌遲,過程只能用慘不忍聞來形容,為什么他會得到這種下場?
- ppt如何制作木紋相框?ppt木紋邊框效果制作技巧
