[英]How to allow, and limit to one “.” (period) character in a TextBox? (C# winforms)
I have this code from MSDN that allows only numeric characters into a TextBox. 我从MSDN获得了这段代码,该代码仅允许将数字字符插入到TextBox中。 But I can't modify it to accept a "."
但是我无法修改它以接受“。” as an input and limit to one.
作为输入并限制为一个。
Ex: 12.50 valid!
236.3247 valid!
2..5 invalid
//other non-numeric input invalid
Considering the code below: 考虑以下代码:
private bool nonNumberEntered = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
nonNumberEntered = true;
}
}
}
if (Control.ModifierKeys == Keys.Shift)
{
nonNumberEntered = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
e.Handled = true;
}
}
Kindly post your modified code. 请张贴修改后的代码。 Thanks a lot.
非常感谢。
I would just validate the field as a Culture-sensitive number after they tab off or on a form submit. 在他们将标签或表单提交后,我只需要将该字段验证为对文化敏感的数字即可。 It's not really necessary or valuable to actually stop them from pressing .
真正阻止他们施压并不是真正必要或有价值的。 twice in the field.
在现场两次。 Often I find that kind of thing annoying, because I'm modifying what was there and I just haven't finished...
我经常觉得这种事情很烦人,因为我正在修改那里的内容,但还没有完成...
Use double.TryParse to test it properly. 使用double.TryParse对其进行正确测试。
I have a textbox that I only want digits and commas in, so it's similar to what you have. 我有一个只希望输入数字和逗号的文本框,所以它与您所拥有的相似。
I'd just run a regex on textbox.Text
to match digits and zero or one decimal points with each key press. 我只需要在
textbox.Text
上运行一个正则表达式textbox.Text
使每次按键匹配数字和零或一个小数点。 If the string that would be created doesn't match, then just disallow that character. 如果要创建的字符串不匹配,则禁止该字符。
I think a .NET example is "^\\d*.?\\d*$" 我认为一个.NET示例是“ ^ \\ d *。?\\ d * $”
From left to right: 从左到右:
Not exactly what you have above but that would work. 上面的内容与您的不完全相同,但可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.