如何在不使用keypress选项的情况下验证数字
为什么Char.IsNumber
或.IsDigit
无效
或者我应该使用正则表达式进行验证
private bool ValidateContact()
{
if (Char.IsNumber(textBox4.Text)){
return true;
}
答案 0 :(得分:7)
您只需解析数字:
private bool ValidateContact()
{
int val;
if (int.TryParse(textBox4.Text, out val))
{
return true;
}
else
{
return false;
}
}
您正在尝试为char
调用为string
编写的方法。您必须单独完成所有操作,或使用更容易使用的方法,如上面的代码。
答案 1 :(得分:3)
为什么不是Char.IsNumber或.IsDigit正在工作
因为Char.IsDigit
想要char
而不是string
。所以你可以检查所有字符:
private bool ValidateContact()
{
return textBox4.Text.All(Char.IsDigit);
}
或 - 更好,因为IsDigit
includes unicode characters - 使用int.TryParse
:
private bool ValidateContact()
{
int i;
return int.TryParse(textBox4.Text, out i);
}
答案 2 :(得分:1)
将字符串解析为:
private bool ValidateContact()
{
int n;
return int.TryParse(textbox4.Text, out n);
}
答案 3 :(得分:0)
如此处http://codepoint.wordpress.com/2011/07/18/numeric-only-text-box-in-net-winforms/所述: -
我们可以在.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;
}
}
答案 4 :(得分:0)
您应该使用
int n;
bool isNumeric = int.TryParse("123", out n);
不是Char.IsNumber()
因为只测试一个角色。
答案 5 :(得分:0)
尝试在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在this问题
上的答案答案 6 :(得分:0)
您也可以使用正则表达式。
if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
你也可以检查,文本框只允许数值: