0

我在 Visual Studio 2012 中工作,我无法通过标签为我在多年期间创建的文本框显示简单的错误消息。例如,如果用户在 txtYears 文本框中输入“dfasdfsa”,则会显示错误“年份必须是数值”。为了更清楚,我将提供 ID 的含义。

txtPrincliple = Priciple amount for a loan
txtYears = duration of the loan in years
lblResult = Result to the button click and the solution 
rblYears = radiobuttonList for duration in years
MonthlyPayment() = is a created method that returns the Monthly payment from provide input

  protected void Button1_Click(object sender, EventArgs e)
   {
    bool error = false;
    //Display Error if non numeric is entered
    if (!double.TryParse(txtPrinciple.Text, out principle))
    {
        error = true;
        lblResult.Text = "The principle must be a numeric value!";
    }

    //Get the values
    if (rblYears.SelectedIndex == 0)
        years = 15;
    else if (rblYears.SelectedIndex == 1)
        years = 30;
    else
        double.TryParse(txtYears.Text, out years);
    //Display Error if custom duration is entered
    if (!double.TryParse(txtYears.Text, out years))
    {
        error = true;
        lblResult.Text = "The years must be a numeric value!";
    }
    //Get interest rate value
    double.TryParse(ddlInterestRate.SelectedValue, out interest);
    //Output the Monthly Payment if no errors
    if (!error)
    {
        lblResult.Text = string.Format("Your total monthly payment is {0}{1:0.00}",   "$", MonthlyPayment());
    }
 }
4

1 回答 1

2

据我所知,问题似乎来自这样一个事实,即即使用户从 RBL 中选择了某些内容,您也会进行错误验证。我不完全确定我理解了这个问题,但是不是很清楚。

如果您将其更改为,它应该可以工作

//Get the values
    if (rblYears.SelectedIndex == 0)
        years = 15;
    else if (rblYears.SelectedIndex == 1)
        years = 30;
    else
    {
        //Display Error if custom duration is entered
        if (!double.TryParse(txtYears.Text, out years))
        {
            error = true;
            lblResult.Text = "The years must be a numeric value!";
        }
    }

我还删除了多余的第一个 TryParse(因为您在验证时这样做)

于 2013-06-06T02:09:23.223 回答