1

我想将所有列表框项目的总值显示到文本框中。

调试器显示这些值的格式如下:£00.00\r\n.

本质上,我想分解项目字符串,然后将其转换为双精度(或小数),将每个项目加在一起最终得出总和。

我曾尝试使用.Replace替换£ \r\n,但这似乎只适用于第一个值,而不适用于其余值。

任何有关如何解决此问题的帮助或建议将不胜感激。

(使用 Visual Studio 2012,使用 C# 的 WPF)

编辑——提供的代码清单:

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
}

当我尝试此代码时,结果为£1.00and £40.00equals 48。不太清楚为什么,但希望它能帮助那些比我有更多经验的人。

4

1 回答 1

1

一方面,您将trimmed在每次迭代中完全替换 的内容。我将循环更改为:

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

当你这样做时

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

因为trimmed是一个字符串,所以发生的事情是您正在添加i字符串的第 th 个字符的值——如果列表框中的行数多于trimmed. 您可能得到 48,因为这是字符“0”的整数值。

于 2014-05-08T13:47:01.533 回答