How to check only number in winform?

How to check a number without using the keypress option why isnt Char.IsNumberor .IsDigitworks or should I use a regex expression to check

private bool ValidateContact()
{
    if (Char.IsNumber(textBox4.Text)){
        return true;
}
+4
source share
7 answers

You can simply analyze the number:

private bool ValidateContact()
{
    int val;
    if (int.TryParse(textBox4.Text, out val))
    {
       return true;
    }
    else
    {
        return false;
    }
}

You are trying to call a method that is written for charfor string. You should do them all separately or use a method that is much easier to use, for example, the above code.

+6
source

why isnt Char.IsNumber or .IsDigit working

Char.IsDigit char a 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);
}
+3

:

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

http://codepoint.wordpress.com/2011/07/18/numeric-only-text-box-in-net-winforms/: -

.Net Windows Forms Key Press.

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

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

Char.IsNumber(), .

0

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

?

. .

0

.

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

, :

, ?

0

Source: https://habr.com/ru/post/1545027/


All Articles