Anon Anon - 3 months ago 14
C# Question

Need to validate textbox for a value

I have a textbox which needs validation upon clicking my "Add" button.

The first check works fine when the other two checks aren't in the code.

The bottom two checks are fine if I enter a value into the textbox. However when I have all three checks, when there isn't a value, the program throws back an error saying


"input string was not in correct format".


if (txtAge.Text == "")
{
message += "<br>Please fill in your Age.</br>";
}
if (Convert.ToInt32(txtAge.Text) > 120)
{
message += "<br>Age cannot be greater than 120</br>";
}
if (Convert.ToInt32(txtAge.Text) < 6)
{
message += "<br>Age cannot be less than 6</br>";
}

Answer

If you are sure that input string is empty or valid number then you can use:

        if (txtAge.Text == "")
        {
            message += "<br>Please fill in your Age.</br>";
        }
        else{
            if (Convert.ToInt32(txtAge.Text) > 120)
            {
                message += "<br>Age cannot be greater than 120</br>";
            }
            if (Convert.ToInt32(txtAge.Text) < 6)
            {
                message += "<br>Age cannot be less than 6</br>";
            }
        }

otherwise you should also use int.TryParse method to insure that string is valid number.