Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate only number in winform?

Tags:

c#

winforms

How to validate for numbers without using keypress option why isnt Char.IsNumber or .IsDigit working or should I use regex expression for validation

private bool ValidateContact()
{
    if (Char.IsNumber(textBox4.Text)){
        return true;
}
like image 276
skates008 Avatar asked Jun 18 '14 07:06

skates008


Video Answer


2 Answers

You could simply parse 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 char for string. You have to do them all separately, or use a method that is much easier to use, like the above code.

like image 76
Patrick Hofman Avatar answered Sep 28 '22 08:09

Patrick Hofman


why isnt Char.IsNumber or .IsDigit working

because Char.IsDigit wants a char not a string. So you could check all characters:

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

or - better because IsDigit includes unicode characters - use int.TryParse:

private bool ValidateContact()
{
    int i;
    return int.TryParse(textBox4.Text, out i);
}
like image 40
Tim Schmelter Avatar answered Sep 28 '22 10:09

Tim Schmelter