C#的winform中如何控制TextBox中只能输入数字?
问题如题
------解决方案--------------------在TextBox的KeyPress事件里判断输入值的ASC码,如果不为数字就把e.Handled设为Ture,取消KeyPress事件
------解决方案--------------------maxLength屬性可以設置長度
------解决方案--------------------参考这个帖子,有n多种方法
http://community.csdn.net/Expert/topic/5386/5386616.xml?temp=.9118158
------解决方案--------------------KeyPress事件里
------解决方案--------------------这种方法好像没人用?
把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);
}
------解决方案--------------------继承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);