0
// Calculating and diplaying pricing in list.
for (double MAX = 4.25; MAX >= MIN; MAX -= 0.05)
{
    Price = (X * MAX);
    prices = Price.ToString("c");
    listFinances.Items.Add(prices);
}

---

private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
    string TotalPrice = listFinances.SelectedItem.ToString();
    double stateIncentive = (Convert.ToDouble(TotalPrice) / 4);
    txtStateTax.Text = stateIncentive.ToString();
}

So I'm trying to take a ListBox of string currency values, turn them into a double, divide them by 4, and display the result in a TextBox. The user will select the ListBox value and the program should automatically divide by 4 and display.

It's not working however. The program always does an exception throw when you click the ListBox item. The exception is thrown at:

double stateIncentive = (Convert.ToDouble(TPrice) / 4);

saying that:

It's not in the correct format.

Can someone help me out here?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Sero
  • 161
  • 8
  • 2
    Post the exact exception that is thrown. Also I cannot find `TPrice` anywhere in your code, you need to post all relevant code. – somesoaccount Nov 03 '15 at 22:03

2 Answers2

3

You add your strings with the currency symbol. If you want to parse the string back to a double (but it is better use a decimal) you need to tell the conversion that you have that symbol and ignore it

private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
    string TotalPrice = listFinances.SelectedItem.ToString();
    decimal stateIncentive = decimal.Parse(TotalPrice, NumberStyles.Currency, CultureInfo.CurrentCulture) / 4);
    txtStateTax.Text = stateIncentive.ToString();
}

I have used decimal instead of double because the decimal type is more adapt to handle money values. I suggest to make the same change in the for..loop that fill the list (Just use the suffix m to specify constant decimal values (IE. 4.25m and 0.05m)

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
1

You are trying to convert a currency string to double so you should Try like this:

double stateIncentive = (Double.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);

Or would be better if using decimal (Read this to know why):

decimal stateIncentive = (decimal.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);

The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) refer to MSDN:Double.Parse Method (String, NumberStyles)

Community
  • 1
  • 1
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109