【问题标题】:Display total value of all listbox items显示所有列表框项目的总值
【发布时间】:2014-05-08 13:30:31
【问题描述】:

我想在一个文本框中显示所有列表框项目的总值。

调试器显示这些值的格式如下:£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.00£40.00 的结果等于 48。不太清楚为什么,但希望它能帮助那些比我有更多经验的人。

【问题讨论】:

  • 向我们展示您的尝试,我们可以从那里开始。就您的问题而言,如果不了解您的 UI 元素是如何创建的以及您如何尝试执行计算,就不可能为您提供一个完整且有意义的解决方案。请编辑您的问题并添加相关代码。
  • 感谢您的回复。我已经发布了代码清单。希望代码和cmets不言自明,如果没有,我会修改帖子。

标签: c# wpf listboxitems


【解决方案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 是一个字符串,所以发生的事情是您正在添加字符串的ith 字符的值---如果列表框中的行数多于那里,这可能会使您的程序崩溃是trimmed 中的字符。您可能得到 48,因为这是字符“0”的整数值。

【讨论】:

  • 谢谢。它不是 100% 工作的,但你肯定让我走上了正确的轨道。回读时似乎很明显。荣誉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
相关资源
最近更新 更多