I have a textbox that I am using to the end user to submit their phone number. I want to be able to evaluate the textbox each time the user hit the submit button. My code work great the first time the end user clicks the button. If they had to fix an error in the textbox and click the button again, the Number is not evaluated again by the TryParse
and the Number is set to 0. Can some please tell me I have use the TryParse more than once?
string NumberLength = TextBoxPhoneNumber.Text;
int Number;
if (int.TryParse(NumberLength, out Number))
{
//I parsed the number out. Now lets get the length
NumberLength = Number.ToString(CultureInfo.InvariantCulture);
if (NumberLength.Length > 10)
{
LblInfo.Visible = true;
LblInfo.ForeColor = Color.Red;
LblInfo.Text = "Phone number can not be longer than 10 digits!";
boolIsValid = false;
}
else if (NumberLength.Length < 10)
{
LblInfo.Visible = true;
LblInfo.ForeColor = Color.Red;
LblInfo.Text = "Phone number can not be shorter than 10 digits!";
boolIsValid = false;
}
}
Try adding an else to the end of the if to turn the error message off again like this:
string NumberLength = TextBoxPhoneNumber.Text;
int Number;
if (int.TryParse(NumberLength, out Number))
{
//I parsed the number out. Now lets get the length
NumberLength = Number.ToString(CultureInfo.InvariantCulture);
if (NumberLength.Length > 10)
{
LblInfo.Visible = true;
LblInfo.ForeColor = Color.Red;
LblInfo.Text = "Phone number can not be longer than 10 digits!";
boolIsValid = false;
}
else if (NumberLength.Length < 10)
{
LblInfo.Visible = true;
LblInfo.ForeColor = Color.Red;
LblInfo.Text = "Phone number can not be shorter than 10 digits!";
boolIsValid = false;
}
else
{
LblInfo.Visible = false;
boolIsValid = true;
}
}
else
{
LblInfo.Visible = true;
LblInfo.ForeColor = Color.Red;
LblInfo.Text = "Phone number can only contain digits!";
boolIsValid = false;
}