Rhys Hamilton
Rhys Hamilton

Reputation: 48

Display total value of all listbox items

I would like to display the total value of all listbox items in to a textbox.

The debugger has shown that the the values are formatted like so: £00.00\r\n.

Essentially, I'd like to break down the item string and then convert it to a double (or decimal), adding each item together to finally give the total sum.

I have tried using .Replace to replace £ \r\n but this only ever seems to work with the first value and not with the rest.

Any help or suggestions as to how to approach this problem would be greatly appreciated.

(Working with Visual Studio 2012, WPF using C#)

Edit -- Code listing provided:

private string trimmed;
private int total;

/// <summary>
/// Calculate the total price of all products
/// </summary>
public void calculateTotal()
{
    foreach (object str in listboxProductsPrice.Items)
    {
        trimmed = (str as string).Replace("£", string.Empty);
        trimmed = trimmed.Replace("\r\n", string.Empty);
        //attempt to break string down
    }

    for (int i = 0; i < listboxProductsPrice.Items.Count - 1; i++)
    {
        total += Convert.ToInt32(trimmed[i]);
    }
    //unsure about this for, is it necessary and should it be after the foreach?

    double add = (double)total;
    txtbxTotalPrice.Text = string.Format("{0:C}", add.ToString());
    //attempt to format string in the textbox to display in a currency format
}

When I try this code, the results for £1.00 and £40.00 equals 48. Not quite sure why, but hopefully it will help those with a lot more experience than myself.

Upvotes: 1

Views: 1761

Answers (1)

Andrew
Andrew

Reputation: 5083

For one thing, you're entirely replacing the content of trimmed at each iteration. I'd change the loop to:

foreach (object str in listboxProductsPrice.Items)
{
    trimmed = (str as string).Replace("£", string.Empty);
    trimmed = trimmed.Replace("\r\n", string.Empty);
    total += Convert.ToInt32(trimmed);
}

When you did this

total += Convert.ToInt32(trimmed[i]);

since trimmed is a string, what was happening is that you're adding the value of the ith character of the string---which might crash your program if there are more lines in the listbox than there are characters in trimmed. You're probably getting 48 since that's the integer value of the character "0".

Upvotes: 1

Related Questions