Basically, I need to add resulta + resultb + resultc + the previously defined propertyPrice together to get a total, then show the total in a text box. Resulta/b/c are calculated based off propertyPrice * a constant, property price is input by the user.
I did it without try-catch and was getting format exceptions.
int propertyPrice;
if (Int32.TryParse(propertyPriceTextBox.Text, out propertyPrice))
{
stateSalesTaxTextBox.Text = (stateSalesTax * propertyPrice).ToString("c");
if (residentialRadioButton.Checked == true)
comissionTextBox.Text = (residentialCom * propertyPrice).ToString("c");
if (commercialRadioButton.Checked == true)
comissionTextBox.Text = (commercialCom * propertyPrice).ToString("c");
if (hillsRadioButton.Checked == true)
countySalesTaxTextBox.Text = (hilssTax * propertyPrice).ToString("c");
if (pascoRadioButton.Checked == true)
countySalesTaxTextBox.Text = (pascoTax * propertyPrice).ToString("c");
if (polkRadioButton.Checked == true)
countySalesTaxTextBox.Text = (polkTax * propertyPrice).ToString("c");
decimal resulta;
decimal resultb;
decimal resultc;
try
{
resulta = decimal.Parse(countySalesTaxTextBox.Text);
resultb = decimal.Parse(stateSalesTaxTextBox.Text);
resultc = decimal.Parse(comissionTextBox.Text);
}
catch (FormatException)
{
}
decimal totalPrice = (resulta + resultb + resultc + propertyPrice);
totalPriceTextBox.Text = totalPrice.ToString("c");
}
Use decimal.TryParse; this will allow you to check whether the string is valid or not.
decimal resulta;
decimal resultb;
decimal resultc;
if (!decimal.TryParse(countySalesTaxTextBox.Text, out resulta))
{
//take appropriate action here
}
if (!decimal.TryParse(stateSalesTaxTextBox.Text, out resultb))
{
//take appropriate action here
}
if (!decimal.TryParse(comissionTextBox.Text, out resultc))
{
//take appropriate action here
}
I'd like to take the opportunity to advise you to change your variable names:
resulta should be countySalesTaxRateresultb should be stateSalesTaxRateresultc should be commissionRatedecimal resulta = 0;
decimal resultb = 0;
decimal resultc = 0;
decimal.TryParse(countySalesTaxTextBox.Text, out resulta);
decimal.TryParse(stateSalesTaxTextBox.Text, out resultb);
decimal.TryParse(comissionTextBox.Text, out resultc);
If it can't Parse the value, it will remain 0. TryParse returns a true if it successfully parses, so if you want to display a message when it doesn't, just check for TryParse == false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With