如果文本框为空,则标签会引发错误

时间:2011-11-23 16:46:12

标签: c#

我有下面的代码工作正常,但如果我将文本框留空,则会抛出错误。我想首先检查是否有任何空白然后在lblSalary.Text中抛出一条错误消息。我怎么能重新写这个? C#

由于

    protected void Button1_Click(object sender, EventArgs e)
    {
        Double AnnualHours;
        AnnualHours = Convert.ToDouble(txtAnnualHours.Text);
        Double Rate;
        Rate = Convert.ToDouble(txtRate.Text);
        Double Salary;
        Salary = (AnnualHours * Rate);
        lblSalary.Text = "$" + Salary.ToString();
    }
}

2 个答案:

答案 0 :(得分:4)

而不是convert.ToDouble使用double.TryParse并处理返回false的情况。

double AnnualHours;
if (!double.TryParse(txtAnnualHours.Text, out AnnualHours))
{
    // Set label text here, as we couldn't convert to a double
}
else
{
    // AnnualHours contains the double value.
}

注意:因为您正在处理金钱,所以您应该使用decimal类型,而不是双重类型。十进制可以正确地正确表示基数10(123,157.2,0.5),而双数不能正确表示。

见这里:decimal vs double! - Which one should I use and when?

答案 1 :(得分:1)

使用Double.TryParse()以安全的方式解析字符串

protected void Button1_Click(object sender, EventArgs e)
{
    double annualHours = 0;
    double.TryParse(txtAnnualHours.Text, out annualHours);
    double rate = 0;
    double.TryParse(txtRate.Text, out rate);
    double salary = (annualHours * rate);
    lblSalary.Text = "$" + salary.ToString();
}

如果您需要进行一些条件计算取决于是否提供了值(用户在文本框中输入了有效数字):

bool isAnnualHoursValid = double.TryParse(txtAnnualHours.Text, out annualHours);
if (isAnnualHoursValid)
{
     // ask user to enter valid value or use some default
}