[英]Format text box to accept only numbers and white spaces and plus sign
I am trying to make a text-box
which will only accept numbers, white spaces and plus sign.我正在尝试制作一个只接受数字、空格和加号的text-box
。
Currently I have done something like this in KeyPressEvent
of the textbox
目前我在textbox
KeyPressEvent
中做了这样的事情
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) &&!char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
I want to accept the +
sign as well我也想接受+
号
Update更新
I did handle the !char.IsSymbol(e.KeyChar)
but it will accept the =
sign as well with the +
我确实处理了!char.IsSymbol(e.KeyChar)
但它也会接受=
符号和+
Any help!!!任何帮助!!!
Thanks谢谢
For having "during input" control and validating control, you can make something like that.对于“输入期间”控制和验证控制,您可以进行类似的操作。
But you'll have many things in your textbox (1+++ +2 34+), which doesn't mean a lot...但是你的文本框中会有很多东西(1+++ +2 34+),这并不意味着很多......
textBox.KeyDown += (sender, e) =>
{
if (!(
//"+
e.KeyCode == Keys.Add ||
//numeric
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
//space
e.KeyCode == Keys.Space))
{
e.Handled = true;
}
};
textBox.Validating += (sender, eventArgs) =>
{
var regex = new Regex(@"[^0-9\+ ]+");
textBox.Text = regex.Replace(textBox.Text, string.Empty);
};
Strictly speaking you could append严格来说你可以追加
&& !e.KeyChar == '+'
to your criteria and it should work as far as keyboard input is concerned , but if the goal is to only allow numeric input the .net control library also contains a NumericUpDown control that can do the trick.根据您的标准,就键盘输入而言,它应该可以工作,但如果目标是只允许数字输入,.net 控件库还包含一个可以解决问题的 NumericUpDown 控件。
Added添加
var reg = new Regex(@"^\\+?(\\d[\\d-. ]+)?(\\([\\d-. ]+\\))?[\\d-. ]+\\d$");
as regex作为正则表达式
This works fine for me:这对我来说很好用:
if (!(char.IsLetter(e.KeyChar) && (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar) && !(e.KeyChar == '.'))
{
e.Handled = true;
}
I added the char.IsControl because it allows you to use Backspace in a typeerror case.我添加了 char.IsControl 是因为它允许您在类型错误的情况下使用 Backspace。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.