我想在列表框中总共花很多钱,但是我做不到,怎么做。
我试图得到很多,但是我失败了。
double totalamount = 0;
for (int i = 0; i <= lstProductQuantity.Items.Count - 2; i++)
{
totalamount = double.Parse(textBox2.Text);
}
textBox2.Text = totalamount.ToString();
我认为这是错误的,请帮助我。
实际上,它应该可以得到所有少量的总和,但是我什么也没想到。
答案 0 :(得分:0)
这是你的问题。
totalamount = double.Parse(textBox2.Text);
将此更改为
totalamount += double.Parse(textBox2.Text);
看起来您只获得了最后一个条目,因为您总是在重写totalamount变量。 这等效于
totalamount = totalamount + double.Parse(textBox2.Text);
正如Mong Zhu指出的那样,在解析时,您应始终检查异常。如果文本不是数字会怎样?可能会发生异常。始终将其包装在try catch块中。
顺便说一句,我也注意到for循环中出现了奇怪的情况:
for (int i = 0; i <= lstProductQuantity.Items.Count - 2; i++)
为什么-2?为什么不包括最后一项?我认为应该是这样的:
for (int i = 0; i < lstProductQuantity.Items.Count; i++)
或
for (int i = 0; i <= lstProductQuantity.Items.Count -1 ; i++)
这对我有用:
double totalamount = 0;
for (int i = 0; i < lstProductQuantity.Items.Count; i++) {
totalamount += lstProductQuantity[i];
}
textBox2.Text = totalamount.ToString();
此外,马克·雷德曼(Mark Redman)通过尝试解析为您提供了绝佳的解决方案。结合两者,您将获得不错的解决方案
答案 1 :(得分:0)
尝试[未测试]:
double totalamount = 0;
for (int i = 0; i < lstProductQuantity.Items.Count; i++)
{
double itemAmount = 0;
if(double.TryParse(lstProductQuantity.Items[i], out itemAmount))
{
totalamount += itemAmount;
}
}
textBox2.Text = totalamount.ToString();
尽管这可能可行,但您应该使用与填充列表框相同的数据进行计算。即准备数据,然后将其呈现给可视控件。