文本框验证,带符号的整数
TextBox validating, integer with symbol
我想限制用户只能在文本框中输入整数(不是双精度)和符号 ","
。我试过这个代码,但是当我试图删除错误的输入时,它总是弹出消息框。
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.");
}
当整个输入从头到尾包含数字和逗号时,^[0-9,]*$
正则表达式 returns 为真。
如果您只需要使用 ,
作为小数点分隔符的整数,请使用
^\d+(?:,\d+)?$
如果要允许使用 ,
的整数作为数字分组(千位分隔符)符号,请使用
^\d{1,3}(?:,\d{3})*$
要处理 Key.Back
键,您需要在 KeyDown/KeyPress 事件处理程序中实现您想要的行为,请参阅 How can I determine if the Backspace has been pressed in the KeyPress event?。
我想限制用户只能在文本框中输入整数(不是双精度)和符号 ","
。我试过这个代码,但是当我试图删除错误的输入时,它总是弹出消息框。
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.");
}
当整个输入从头到尾包含数字和逗号时,^[0-9,]*$
正则表达式 returns 为真。
如果您只需要使用 ,
作为小数点分隔符的整数,请使用
^\d+(?:,\d+)?$
如果要允许使用 ,
的整数作为数字分组(千位分隔符)符号,请使用
^\d{1,3}(?:,\d{3})*$
要处理 Key.Back
键,您需要在 KeyDown/KeyPress 事件处理程序中实现您想要的行为,请参阅 How can I determine if the Backspace has been pressed in the KeyPress event?。