Reputation: 2313
I have the code below which works fine, but if I leave the text boxes blank it throws an error. I would like to first check if any are blank then throw an error message in lblSalary.Text. How could I re-write this? C#
Thanks
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();
}
}
Upvotes: 1
Views: 332
Reputation: 32428
Instead of convert.ToDouble
use double.TryParse
and handle the case where it returns 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.
}
NOTE: Because you're dealing with money, you should use the decimal type, not the double type. Decimal can correctly represent base 10 numbers (123, 157.2, 0.5) exactly, whereas double cannot.
See here: decimal vs double! - Which one should I use and when?
Upvotes: 4
Reputation: 62504
Use Double.TryParse() to parse string in safe manner
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();
}
If you need to do some conditional calculations depends on whether value was provided or not (user entered a valid number in textbox):
bool isAnnualHoursValid = double.TryParse(txtAnnualHours.Text, out annualHours);
if (isAnnualHoursValid)
{
// ask user to enter valid value or use some default
}
Upvotes: 1