Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble adding calculated variables c#

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");  
}
like image 886
Jamaul Smith Avatar asked Dec 01 '25 02:12

Jamaul Smith


2 Answers

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 countySalesTaxRate
  • resultb should be stateSalesTaxRate
  • resultc should be commissionRate
like image 193
phoog Avatar answered Dec 02 '25 14:12

phoog


decimal 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

like image 21
Adam Plocher Avatar answered Dec 02 '25 14:12

Adam Plocher