如何只validationwinform中的数字?

如何在不使用Char.IsNumber选项的情况下validation数字为什么Char.IsNumber.IsDigit不起作用或者我应该使用正则表达式进行validation

 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工作

因为Char.IsDigit想要一个char而不是一个string 。 所以你可以检查所有字符:

 private bool ValidateContact() { return textBox4.Text.All(Char.IsDigit); } 

或者 – 更好,因为IsDigit 包含unicode字符 – 使用int.TryParse

 private bool ValidateContact() { int i; return int.TryParse(textBox4.Text, out i); } 

将字符串解析为:

 private bool ValidateContact() { int n; return int.TryParse(textbox4.Text, out n); } 

你应该使用

 int n; bool isNumeric = int.TryParse("123", out n); 

不是Char.IsNumber() ,因为它只测试一个字符。

如此处所述http://codepoint.wordpress.com/2011/07/18/numeric-only-text-box-in-net-winforms/ : –

我们可以在.Net Windows窗体应用程序中创建仅限数字的文本框,并在Key Press Event中添加以下代码。

仅限数字文本框

 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; } } 

您也可以使用正则表达式。

  if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text)) { MessageBox.Show("Please enter only numbers."); textBox1.Text.Remove(textBox1.Text.Length - 1); } 

你也可以检查,文本框只允许数值:

如何制作仅接受数字的文本框?

尝试在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; } } 

为什么控制按键?

因为在输入值之后警告用户不是从用户获得输入的有效方式。 您可以阻止用户在用户输入时输入非有效值,而不是这样做。

基于马特汉密尔顿在这个问题上的答案