2017-06-11 37 views
0

我想从列表框中将它们添加到组合框后,计算项目的总价格。在列表框中,我有两种类型的物品和ts价格。我希望看到总价格增加,因为我将每个项目(单击addButton)添加到组合框。但是我看到的是该项目被添加到组合框,但我只看到单个项目价格而不是价格总和。这是我的代码示例。如何使用for循环来总结项目

private void addButton_Click(object sender, EventArgs e) 
{ 
    decimal price;  // variables to holds the price 

    decimal total = 0; // variables to hold the total 
    int counter; 

    for (counter=0; counter <= 5; counter++) 
    {  
     price = decimal.Parse(priceLabel2.Text); 
     // add items price 
     total += price; 

     // display the total amount 
     costLabel.Text = total.ToString("c"); 
    } 

任何帮助,将不胜感激,

+0

如果添加4个项目,显示的总数(当前)是否只添加最后一个? – mjwills

+0

是的,它只显示最后一个。 –

+1

如果您发布的代码与您提供的描述相关,那么这将更容易。你解释一下列表框和组合框,然后发布处理一些标签的代码。另外,请修复缩进。 –

回答

4

变化:

private void addButton_Click(object sender, EventArgs e) 
    { 
     decimal price;  // variables to holds the price 

     decimal total = 0; // variables to hold the total 
     int counter; 

      for (counter=0; counter <= 5; counter++) 
      { 

      price = decimal.Parse(priceLabel2.Text); 
      // add items price 
      total += price; 

      // display the total amount 
      costLabel.Text = total.ToString("c"); 
      } 

到:

decimal total = 0; // variables to hold the total 

    private void addButton_Click(object sender, EventArgs e) 
    { 
     decimal price; // variables to holds the price 

     int counter; 

     for (counter = 0; counter <= 5; counter++) 
     { 
      price = decimal.Parse(priceLabel2.Text); 
      // add items price 
      total += price; 

      // display the total amount 
      costLabel.Text = total.ToString("c"); 
     } 
    } 

这里最重要的变化是移动的总可变功能。这意味着该值在点击之间保持不变。如果你把它放在函数中,它会在每次点击时重置为0(这不是你想要的)。

+5

我没有投票你的问题,但你可以做到以下几点:(1)修正缩进,(2)解释为什么在函数外面移动变量'total'解决了问题。我相信这就是让你低估的原因。另外还有另一种方法:在函数的开始处从'costLabel'中获取当前的总值,这样就没有外部变量。 – Rafalon

+0

你没有解释任何东西。你刚刚粘贴了一个正确的版本... – FCin

+0

伟大的反馈 - 谢谢@Rafalon和FCin。我根据您的意见进行了一些更改。再次感谢! – mjwills