作者unfun (不好玩)
看板C_Sharp
标题[问题] TextBox只允许输入数字及负号
时间Thu Mar 27 10:30:36 2014
private void endSpeed_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsNumber(e.KeyChar) &&
!Char.IsPunctuation(e.KeyChar) &&
!Char.IsControl(e.KeyChar))
{
e.Handled = true;
}
else if (Char.IsPunctuation(e.KeyChar))
{
if (endSpeed.Text.LastIndexOf('.') != -1)
{
e.Handled = true;
}
if (e.KeyChar == '-')
{
if (this.endSpeed.Text.Length > 0)
e.Handled = true;
}
}
}
目前小弟在网路上搜寻只输入数字的方法,
东拼西凑之下完成了一个堪用的过滤方式。
其主要的逻辑为
1.先筛选掉非数字浮号的字元
2.小数点只能有一个
3.负号只能在第一位
但现在有个问题了,有几个方法无法使用
1.当textbox.text内已经有小数点,无法反白(全选)後输入'.'
2.当textbox.text内有内容,无法反白(全选)後输入'-'
总而言之我的过滤方式无法排除全选後输入这种方法,是否有更好的处理方式。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.129.103.86
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1395887439.A.D7C.html
1F:推 Eleganse:没写过 感觉上可以考虑用正规表示式写在网页客端js码完成 03/27 10:47
2F:→ Eleganse:textbox这个控制项和前端码及後端码都很容易操控到 03/27 10:48
3F:→ pkmu8426:我的话会采用 触发事件 事件中每一次都重新针对 03/27 11:26
4F:→ pkmu8426:textbox中的文字进行整行判断 03/27 11:27
5F:推 GoalBased:写js吧 03/27 12:26
6F:→ talenttb:client js keydown 限制 server regular 检查 03/27 13:07
小弟是C#初学者,以前有一些C++的经验,
我是要做一个视窗软体 截图
http://ppt.cc/GDXR
已经找到解决方法,自问自答一下
http://ideone.com/NKOWRA
※ 编辑: unfun 来自: 220.129.103.86 (03/27 13:41)
7F:→ umi8422:套jquery.validate程式都不用写 03/28 20:48
8F:→ VVll:if(!double.TryParse(input, out d)) error; 04/01 04:39
9F:推 nfsong:用java 写在前台 onkeydown return only key 06/05 21:41