當前位置:編程學習大全網 - 源碼下載 - C# 文本框只能輸入數字

C# 文本框只能輸入數字

代碼如下:

調用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;

}

}

  • 上一篇:開發商城小程序有什麽好處?
  • 下一篇:黑客動畫吧記事本源代碼
  • copyright 2024編程學習大全網