我想将所有列表框项目的总值显示到文本框中。
调试器显示这些值的格式如下:£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
and £40.00
equals 48
。不太清楚为什么,但希望它能帮助那些比我有更多经验的人。