C# 如何在winform中只验证数字?
如何在不使用按键选项的情况下验证数字 为什么C# 如何在winform中只验证数字?,c#,winforms,C#,Winforms,如何在不使用按键选项的情况下验证数字 为什么Char.IsNumber或.IsDigit不起作用 还是应该使用正则表达式进行验证 private bool ValidateContact() { if (Char.IsNumber(textBox4.Text)){ return true; } 您可以简单地解析数字: private bool ValidateContact() { int val; if (int.TryParse(textBox4.T
Char.IsNumber
或.IsDigit
不起作用
还是应该使用正则表达式进行验证
private bool ValidateContact()
{
if (Char.IsNumber(textBox4.Text)){
return true;
}
您可以简单地解析数字:
private bool ValidateContact()
{
int val;
if (int.TryParse(textBox4.Text, out val))
{
return true;
}
else
{
return false;
}
}
您正在尝试调用为char
编写的string
方法。您必须分别执行这些操作,或者使用更易于使用的方法,如上面的代码
为什么Char.IsNumber或.IsDigit不起作用
因为需要的是字符
而不是字符串
。因此,您可以检查所有字符:
private bool ValidateContact()
{
return textBox4.Text.All(Char.IsDigit);
}
或者-更好,因为IsDigit
-使用:
如本文所述:-
通过在按键事件中添加以下代码,我们可以在.Net Windows窗体应用程序中创建纯数字文本框
仅数字文本框
private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
你应该使用
int n;
bool isNumeric = int.TryParse("123", out n);
不是Char.IsNumber(),因为它只测试一个字符。将字符串解析为:
private bool ValidateContact()
{
int n;
return int.TryParse(textbox4.Text, out n);
}
尝试在textbox.KeyPress上按住除数字或小数点以外的所有键
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
为什么要控制按键
因为在用户输入值后提醒用户并不是从用户获取输入的有效方法。
您可以在用户键入时阻止用户输入无效值,而不是执行此操作
基于Matt Hamilton对问题的回答,您也可以使用正则表达式
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
您还可以选中“文本框仅允许数值”:
因为
Char.IsDigit
需要一个Char而不是stringreturn Int.TryParse(textbox4.Text,out t),所以我个人不依赖这个解决方案char.IsDigit
对所有unicode数字返回true。看起来int.TryParse
在这里更合适。@Selman22:这一点很好。我已经相应地编辑了我的答案,并包含了与此相关的内容。您的解决方案将给出一个错误<代码>并非所有代码路径都返回一个值,但如果用户想要输入一个十进制数呢?那么这将不起作用,请尝试使用decimal.TryParse
然后。OP的原始代码似乎不需要这个,所以我忽略了这个。(合同号通常没有小数)@skates008:需要更多帮助吗?@skates008:请不要忘记标记您的问题是否已回答。问题状态为“不使用按键选项”。
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}