validation文本框字段仅用于数字输入。

我创建了一个基于表单的程序,需要一些输入validation。 我需要确保用户只能在距离文本框中输入数值。

到目前为止,我已经检查过Textbox中有一些内容,但是如果它有一个值,那么它应该继续validation输入的值是否为数字:

else if (txtEvDistance.Text.Length == 0) { MessageBox.Show("Please enter the distance"); } else if (cboAddEvent.Text //is numeric) { MessageBox.Show("Please enter a valid numeric distance"); } 

您可以尝试使用TryParse方法,该方法允许您将字符串解析为整数并返回指示操作成功或失败的布尔结果。

 int distance; if (int.TryParse(txtEvDistance.Text, out distance)) { // it's a valid integer => you could use the distance variable here } 

如果要在TextBox中输入信息时阻止用户输入非数字值,可以使用Event OnKeyPress,如下所示:

 private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter } 

如果用户使用鼠标(右键单击/粘贴)将信息粘贴到TextBox中,则此解决方案不起作用,在这种情况下,您应该添加额外的validation。

这是另一个简单的解决方案

 try { int temp=Convert.ToInt32(txtEvDistance.Text); } catch(Exception h) { MessageBox.Show("Please provide number only"); } 

你可以通过客户端的javascript或在文本框上使用一些正则表达式validation器来完成。

使用Javascript

 script type="text/javascript" language="javascript"> function validateNumbersOnly(e) { var unicode = e.charCode ? e.charCode : e.keyCode; if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) { return true; } else { window.alert("This field accepts only Numbers"); return false; } }  

文本框(具有固定的ValidationExpression)

   

你可以这样做

  int outParse; // Check if the point entered is numeric or not if (Int32.TryParse(txtEvDistance.Text, out outParse) && outParse) { // Do what you want to do if numeric } else { // Do what you want to do if not numeric } 

我同意Int.TryParse,但作为替代方案,您可以使用Regex。

  Regex nonNumericRegex = new Regex(@"\D"); if (nonNumericRegex.IsMatch(txtEvDistance.Text)) { //Contains non numeric characters. return false; } 

我有这个扩展,这是一种多用途:

  public static bool IsNumeric(this object value) { if (value == null || value is DateTime) { return false; } if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean) { return true; } try { if (value is string) Double.Parse(value as string); else Double.Parse(value.ToString()); return true; } catch { } return false; } 

它适用于其他数据类型。 应该适合你想做的事情。

  if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false) { lblMessage.Text = string.Empty; lblMessage.Visible = true; lblMessage.ForeColor = Color.Maroon; lblMessage.Text = "You have not entered a number"; return; } 

这是一个解决方案,允许数字只有减号或小数有减号和小数点。 以前的大多数答案没有考虑选定的文字。 如果将文本框的ShortcutsEnabled更改为false,则无法将垃圾粘贴到文本框中(它会禁用右键单击)。 有些解决方案允许您在减号之前输入数据。 请确认我已经抓住了一切!

  private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e) { if (numeric) { // Test first character - either text is blank or the selection starts at first character. if (txt.Text == "" || txt.SelectionStart == 0) { // If the first character is a minus or digit, AND // if the text does not contain a minus OR the selected text DOES contain a minus. if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-"))) return false; else return true; } else { // If it's not the first character, then it must be a digit or backspace if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back)) return false; else return true; } } else { // Test first character - either text is blank or the selection starts at first character. if (txt.Text == "" || txt.SelectionStart == 0) { // If the first character is a minus or digit, AND // if the text does not contain a minus OR the selected text DOES contain a minus. if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-"))) return false; else { // If the first character is a decimal point or digit, AND // if the text does not contain a decimal point OR the selected text DOES contain a decimal point. if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))) return false; else return true; } } else { // If it's not the first character, then it must be a digit or backspace OR // a decimal point AND // if the text does not contain a decimal point or the selected text does contain a decimal point. if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))) return false; else return true; } } } 

要检查值是否为double:

 private void button1_Click(object sender, EventArgs e) { if (!double.TryParse(textBox1.Text, out double myX)) { System.Console.WriteLine("it's not a double "); return; } else System.Console.WriteLine("it's a double "); }