Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 文本框验证,带符号的整数_C#_Regex_Validation_Textbox - Fatal编程技术网

C# 文本框验证,带符号的整数

C# 文本框验证,带符号的整数,c#,regex,validation,textbox,C#,Regex,Validation,Textbox,我想限制用户只能在文本框中输入整数(而不是双精度)和符号“”,“”。我尝试过这段代码,但当我试图删除错误的输入时,它总是会弹出消息框 if (!System.Text.RegularExpressions.Regex.IsMatch(textBox4.Text, @"^[0-9,-Key.Back]")) { MessageBox.Show("This textbox accepts only alphabetical characters"); //textBox4.Text.

我想限制用户只能在文本框中输入整数(而不是双精度)和符号“
”,“
”。我尝试过这段代码,但当我试图删除错误的输入时,它总是会弹出消息框

if (!System.Text.RegularExpressions.Regex.IsMatch(textBox4.Text, @"^[0-9,-Key.Back]"))
{
    MessageBox.Show("This textbox accepts only alphabetical characters");
    //textBox4.Text.Remove(textBox4.Text.Length - 1);
    //textBox4.Clear();
}
请帮助。

试试这个:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != (char)Keys.Back)
    {
        e.Handled = true;
        MessageBox.Show("Digits, commas and backspace only");
    }
}

我猜您正在
TextChanged
事件处理程序中运行代码。问题在于你的正则表达式。您说您需要允许数字和逗号,但您正在检查是否有数字、
、介于
K
之间的一些范围,以及字符串开头带有文字点的一些字母(
e
y
等)

我想你想把它修好

if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"^[0-9,]*$"))
{
    MessageBox.Show("Please enter only numbers and commas.");
}
当整个输入从头到尾包含数字和逗号时,正则表达式返回true

如果需要只允许使用带
的整数作为小数分隔符,请使用

^\d+(?:,\d+)?$
如果要允许使用带有
的整数作为数字分组(千位分隔符)符号,请使用

^\d{1,3}(?:,\d{3})*$

要处理
Key.Back
键,您需要在KeyDown/KeyPress事件处理程序中实现所需的行为,请参阅。

您不能在regex模式中使用
Key.Back
。在KeyDown/KeyPress事件处理程序中处理此键(请参阅)。