C#的winform中如何控制TextBox中只能输入数字? 问题如题 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 在TextBox的KeyPress事件里判断输入值的ASC码,如果不为数字就把e.Handled设为Ture,取消KeyPress事件 参考这个帖子,有n多种方法http://community.csdn.net/Expert/topic/5386/5386616.xml?temp=.9118158 这种方法好像没人用?把textbox改为对应的就可以用了: private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { if (textBox3.SelectionStart == 0) { if (e.KeyChar.CompareTo('0') == 0 || e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0) { e.Handled = true; } } else { if (e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0) { if (e.KeyChar != '\b') e.Handled = true; } } } 给个最简单的方法: private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { //阻止从键盘输入键 e.Handled = true; if(e.KeyChar>='0' && e.KeyChar <='9') { e.Handled = false; } } *****************************************************************************欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html bool isNumberEnter = true; protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9) { if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9) { if (e.KeyCode != Keys.Back) { isNumberEnter = false; } } } base.OnKeyDown(e); } protected override void OnKeyPress(KeyPressEventArgs e) { if (!isNumberEnter) { e.Handled = true; isNumberEnter = true; } base.OnKeyPress(e); } 用一个.net自带的验证控件就可以了 继承TextBox,然后重写万无一失protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_CHAR: bool isSign = ((int)m.WParam == 45); bool isNum = ((int)m.WParam >= 48) && ((int)m.WParam <= 57); bool isBack = (int)m.WParam == (int)Keys.Back; bool isDelete = (int)m.WParam == (int)Keys.Delete;//实际上这是一个"."键 bool isCtr = ((int)m.WParam == 24) || ((int)m.WParam == 22) || ((int)m.WParam == 26) ||((int)m.WParam == 3); bool isEnter = ((int)m.WParam == 13); if (isEnter && _entertotab) { SendKeys.Send("{TAB}"); break; } if( isNum || isBack || isCtr) { base.WndProc (ref m); } if (isSign) { if (((this.SelectionStart!=0)) || _positive) { break; } base.WndProc (ref m); break; } if (isDelete) { if (_onlyint) break; if (this.Text.IndexOf(".")<0) { base.WndProc (ref m); } } if ((int)m.WParam == 1) { this.SelectAll(); } break; case WM_PASTE: IDataObject iData = Clipboard.GetDataObject();//取剪贴板对象 if(iData.GetDataPresent(DataFormats.Text)) //判断是否是Text { string str = (string)iData.GetData(DataFormats.Text);//取数据 if (MatchNumber(str)) { base.WndProc (ref m); break; } } m.Result = (IntPtr)0;//不可以粘贴 break; default: base.WndProc (ref m); break; } } /// <summary> /// 让TextBox框只能输入数字 /// </summary> /// <param name="textbox">TextBox控件</param> /// <param name="vtt">事件类型</param> /// <param name="minValue">最小值</param> /// <param name="maxValue">最大值</param> public static void ValidNum(System.Windows.Forms.TextBox textbox, ValidTextType vtt, int minValue, int maxValue) { if (textbox.Text=="") return; if (vtt==ValidTextType.TextChange) { if (IsNumeric(textbox.Text)==false||Convert.ToDouble(textbox.Text)<minValue||Convert.ToDouble(textbox.Text)>maxValue) { textbox.Text=textbox.Text.Substring(0,textbox.Text.Length-1); if (textbox.Text.Length>=1) { textbox.SelectionStart=textbox.Text.Length; } } } else if(vtt==ValidTextType.Leave) { if (IsNumeric(textbox.Text)==false) { textbox.Text=textbox.Text.Substring(0,textbox.Text.Length-1); if (textbox.Text.Length>=1) { textbox.SelectionStart=textbox.Text.Length; } } } } /// <summary> /// 是否数字类型 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumeric(string str) { try { double db=Convert.ToDouble(str); return true; } catch { return false; } } /// <summary> /// 验证Text事件类型 /// </summary> public enum ValidTextType { /// <summary> /// TextChange事件 /// </summary> TextChange, /// <summary> /// Leave事件 /// </summary> Leave, /// <summary> /// None /// </summary> None }//在textbox的textchange或leave事件里调用 去掉我自己的几个属性:protected override void WndProc(ref Message m){switch(m.Msg){ case WM_CHAR:bool isSign = ((int)m.WParam == 45);bool isNum = ((int)m.WParam >= 48) && ((int)m.WParam <= 57);bool isBack = (int)m.WParam == (int)Keys.Back;bool isDelete = (int)m.WParam == (int)Keys.Delete;//实际上这是一个"."键bool isCtr = ((int)m.WParam == 24) || ((int)m.WParam == 22) || ((int)m.WParam == 26) ||((int)m.WParam == 3);bool isEnter = ((int)m.WParam == 13);if( isNum || isBack || isCtr){base.WndProc (ref m);}if (isSign){if (((this.SelectionStart!=0)) ){break;}base.WndProc (ref m);break;}if (isDelete){if (this.Text.IndexOf(".")<0){base.WndProc (ref m);}}if ((int)m.WParam == 1){this.SelectAll();}break;case WM_PASTE:IDataObject iData = Clipboard.GetDataObject();//取剪贴板对象if(iData.GetDataPresent(DataFormats.Text)) //判断是否是Text{string str = (string)iData.GetData(DataFormats.Text);//取数据if (MatchNumber(str)) {base.WndProc (ref m);break;}}m.Result = (IntPtr)0;//不可以粘贴break;default:base.WndProc (ref m);break;}} 我一般是用验证,正则就用[0-9]{0,9},因为INT是有范围的。也可以用比较验证,把比较类型设为整型。 比较常用的是正则,当然也有在KeyPress中写的。这两种方式比较快搞定要是自己继承TextBox然后再重写会比较花时间。除非你要把它做成基类以后都用它才值得。 用RegularExpressionValidator关联textbox,然后再validationexpress里面加入正则表达式,这样比较简单 我常用的方式是KeyPress事件中写入if(e.KeyChar>='0' && e.KeyChar <='9'){ e.Handled = false;} 更简单的方法:private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (textBox1.SelectionLength == 0) { if (e.KeyChar.CompareTo('0') == 0 || e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0) { e.Handled = true; } }} 我太菜了,只会这个if(e.KeyChar> = '0 ' && e.KeyChar <= '9 '){ e.Handled = false;} 呵呵, 鼠标右键粘贴时会绕开KeyPress 事件. 都不知道你们在瞎扯什么.参考14楼的吧,消息处理. 没看都上说下我的想法: 在textchange函数里每次change都把内容转化成数字试试,如果错误就删掉刚才键入的字符 private void textbox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar)) //只允许输入数字键和退格键 { e.Handled = true; } } private void textbox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar)) { e.Handled = true; } } /// <summary> /// 只允许录入数字 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tb_KeyPress(object sender, KeyPressEventArgs e) { if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46) { e.Handled = true; } else { if (e.KeyChar == 46 && tb.Text.IndexOf('.') > -1) { e.Handled = true; } } } KeyPress事件: if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == 8 || e.KeyChar == '.')) { e.Handled = true; } 发表于:2007-05-29 20:02:10陈年老帖被lnnneu2009翻出来了。OJ,来结贴哦。 给个最简单的方法:private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e){ //阻止从键盘输入键 e.Handled = true; if(e.KeyChar>='0' && e.KeyChar <='9') { e.Handled = false; }}多条件的:private void TxtUser_KeyPress(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 = TxtUser.Text.Length; if (len < 5) { if (len == 0 && e.KeyChar != '0') { e.Handled = false; return; } else if(len == 0) { MessageBox.Show("编号不能以0开头!"); return; } e.Handled = false; return; } else { MessageBox.Show("编号最多只能输入5位数字!"); } } } else { MessageBox.Show("编号只能输入数字!"); } } 最简单的就是添加KeyPress事件private void NowTime_KeyPress(object sender, KeyPressEventArgs e) { NowTime.ReadOnly = true; } C#调用sfc_os.dll中的5号函数来解除系统文件保护 wpf中textblock disable后,背景色默认为灰色,这个颜色可否改变? 如何强制关闭一个指定的线程 实现局域网内远程关机 C#中显示控制台输出 為什麼Ms的那個SqlHelper里面的方法全部用Static(頂者有分) 如何自动调整图像的光暗及对比度 PropertyGrid如何同时实现动态加载属性和展开? 求教一个问题。 这个SQL语句怎么写? 在VS2008(C#)环境下用什么控件实现vista的透明窗体? c#如何做除法,5/2=3,3/2=2
把textbox改为对应的就可以用了:
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox3.SelectionStart == 0)
{
if (e.KeyChar.CompareTo('0') == 0 || e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0)
{
e.Handled = true;
}
}
else
{
if (e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0)
{
if (e.KeyChar != '\b')
e.Handled = true;
}
}
}
private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//阻止从键盘输入键
e.Handled = true;
if(e.KeyChar>='0' && e.KeyChar <='9')
{
e.Handled = false;
} }
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码) http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
isNumberEnter = false;
}
}
}
base.OnKeyDown(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!isNumberEnter)
{
e.Handled = true;
isNumberEnter = true;
}
base.OnKeyPress(e);
}
万无一失protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_CHAR:
bool isSign = ((int)m.WParam == 45);
bool isNum = ((int)m.WParam >= 48) && ((int)m.WParam <= 57);
bool isBack = (int)m.WParam == (int)Keys.Back;
bool isDelete = (int)m.WParam == (int)Keys.Delete;//实际上这是一个"."键
bool isCtr = ((int)m.WParam == 24) || ((int)m.WParam == 22) || ((int)m.WParam == 26) ||((int)m.WParam == 3);
bool isEnter = ((int)m.WParam == 13);
if (isEnter && _entertotab)
{
SendKeys.Send("{TAB}");
break;
}
if( isNum || isBack || isCtr)
{
base.WndProc (ref m);
}
if (isSign)
{
if (((this.SelectionStart!=0)) || _positive)
{
break;
}
base.WndProc (ref m);
break;
}
if (isDelete)
{
if (_onlyint) break;
if (this.Text.IndexOf(".")<0)
{
base.WndProc (ref m);
}
}
if ((int)m.WParam == 1)
{
this.SelectAll();
}
break;
case WM_PASTE:
IDataObject iData = Clipboard.GetDataObject();//取剪贴板对象
if(iData.GetDataPresent(DataFormats.Text)) //判断是否是Text
{
string str = (string)iData.GetData(DataFormats.Text);//取数据
if (MatchNumber(str))
{
base.WndProc (ref m);
break;
}
}
m.Result = (IntPtr)0;//不可以粘贴
break;
default:
base.WndProc (ref m);
break;
}
}
/// 让TextBox框只能输入数字
/// </summary>
/// <param name="textbox">TextBox控件</param>
/// <param name="vtt">事件类型</param>
/// <param name="minValue">最小值</param>
/// <param name="maxValue">最大值</param>
public static void ValidNum(System.Windows.Forms.TextBox textbox, ValidTextType vtt, int minValue, int maxValue)
{
if (textbox.Text=="")
return;
if (vtt==ValidTextType.TextChange)
{
if (IsNumeric(textbox.Text)==false||Convert.ToDouble(textbox.Text)<minValue||Convert.ToDouble(textbox.Text)>maxValue)
{
textbox.Text=textbox.Text.Substring(0,textbox.Text.Length-1);
if (textbox.Text.Length>=1)
{
textbox.SelectionStart=textbox.Text.Length;
}
}
}
else if(vtt==ValidTextType.Leave)
{
if (IsNumeric(textbox.Text)==false)
{
textbox.Text=textbox.Text.Substring(0,textbox.Text.Length-1);
if (textbox.Text.Length>=1)
{
textbox.SelectionStart=textbox.Text.Length;
}
}
}
} /// <summary>
/// 是否数字类型
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumeric(string str)
{
try
{
double db=Convert.ToDouble(str);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 验证Text事件类型
/// </summary>
public enum ValidTextType
{
/// <summary>
/// TextChange事件
/// </summary>
TextChange,
/// <summary>
/// Leave事件
/// </summary>
Leave,
/// <summary>
/// None
/// </summary>
None
}//在textbox的textchange或leave事件里调用
{
switch(m.Msg)
{
case WM_CHAR:
bool isSign = ((int)m.WParam == 45);
bool isNum = ((int)m.WParam >= 48) && ((int)m.WParam <= 57);
bool isBack = (int)m.WParam == (int)Keys.Back;
bool isDelete = (int)m.WParam == (int)Keys.Delete;//实际上这是一个"."键
bool isCtr = ((int)m.WParam == 24) || ((int)m.WParam == 22) || ((int)m.WParam == 26) ||((int)m.WParam == 3);
bool isEnter = ((int)m.WParam == 13);if( isNum || isBack || isCtr)
{
base.WndProc (ref m);
}
if (isSign)
{
if (((this.SelectionStart!=0)) )
{
break;
}
base.WndProc (ref m);
break;
}
if (isDelete)
{
if (this.Text.IndexOf(".")<0)
{
base.WndProc (ref m);
}
}
if ((int)m.WParam == 1)
{
this.SelectAll();
}
break;
case WM_PASTE:
IDataObject iData = Clipboard.GetDataObject();//取剪贴板对象if(iData.GetDataPresent(DataFormats.Text)) //判断是否是Text
{
string str = (string)iData.GetData(DataFormats.Text);//取数据
if (MatchNumber(str))
{
base.WndProc (ref m);
break;
}
}
m.Result = (IntPtr)0;//不可以粘贴
break;
default:
base.WndProc (ref m);
break;
}
}
也可以用比较验证,把比较类型设为整型。
要是自己继承TextBox然后再重写会比较花时间。除非你要把它做成基类以后都用它才值得。
KeyPress事件中写入
if(e.KeyChar>='0' && e.KeyChar <='9')
{
e.Handled = false;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.SelectionLength == 0)
{
if (e.KeyChar.CompareTo('0') == 0 || e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0)
{
e.Handled = true;
}
}
}
if(e.KeyChar> = '0 ' && e.KeyChar <= '9 ')
{
e.Handled = false;
}
参考14楼的吧,消息处理.
在textchange函数里每次change都把内容转化成数字试试,如果错误就删掉刚才键入的字符
private void textbox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar)) //只允许输入数字键和退格键
{
e.Handled = true;
}
}
{
if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
/// <summary>
/// 只允许录入数字
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tb_KeyPress(object sender, KeyPressEventArgs e)
{ if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
else
{
if (e.KeyChar == 46 && tb.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
}
if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == 8 || e.KeyChar == '.'))
{
e.Handled = true;
}
陈年老帖被lnnneu2009翻出来了。OJ,来结贴哦。
private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//阻止从键盘输入键
e.Handled = true;
if(e.KeyChar>='0' && e.KeyChar <='9')
{
e.Handled = false;
}}
多条件的:private void TxtUser_KeyPress(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 = TxtUser.Text.Length;
if (len < 5)
{
if (len == 0 && e.KeyChar != '0')
{
e.Handled = false; return;
}
else if(len == 0)
{
MessageBox.Show("编号不能以0开头!"); return;
}
e.Handled = false; return;
}
else
{
MessageBox.Show("编号最多只能输入5位数字!");
}
}
}
else
{
MessageBox.Show("编号只能输入数字!");
}
}
{
NowTime.ReadOnly = true;
}