int.TryParse(String,out Number)仅在按钮单击事件中有效一次

时间:2014-12-20 19:35:17

标签: c# asp.net visual-studio-2013 int tryparse

我有一个文本框,我正在向最终用户提交他们的电话号码。我希望每次用户点击提交按钮时都能评估文本框。我的代码在最终用户第一次单击按钮时工作得很好。如果他们必须在文本框中修复错误并再次单击该按钮,则TryParse不会再次评估数字,并且数字设置为0.有些请告诉我,我已经多次使用TryParse ?

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

3 个答案:

答案 0 :(得分:1)

尝试在if的末尾添加else以再次关闭错误消息,如下所示:

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

答案 1 :(得分:0)

为什么你不使用Regex方法?

 using System.Text.RegularExpressions;


 Regex rgx = new Regex("\d");
 if(rgx.IsMatch(number))
 {
     //True
 }

答案 2 :(得分:-1)

如果第二次输入的字符串是数字类型,TRYPARSE会将其转换为int值,但如果输入的值是非数字,则该方法将返回0.请将一些验证仅接受文本中的数字字符串-box !!!