C#验证:限制TextBox只能输入数字并控制输入数字的长度(数字)
一.KeyPress事件
private void txt_loopNum_KeyPress(object sender, KeyPressEventArgs e) { CheckNum(sender, e); }
二.CheckNum方法
public void CheckNum(object sender, KeyPressEventArgs e) { //阻止从键盘输入键 e.Handled = true; if (e.KeyChar >= '0' && e.KeyChar <= '9' || (e.KeyChar == (char)8)) { if (e.KeyChar == (char)8) { e.Handled = false; return; } else { int len_lookNum = ((TextEdit)sender).Text.Trim().Length; if (len_lookNum < 8) { if (len_lookNum == 0 && e.KeyChar != '0') { e.Handled = false; return; } else if (len_lookNum== 0) { e.Handled = true; return; } e.Handled = false; return; } else { MessageBox.Show("输入数字过大"); } } } }
清清软件园 http://sillysoft.taobao.com