C# 如何使用for循环对项目求和

C# 如何使用for循环对项目求和,c#,C#,我试图在从列表框将项目添加到组合框后计算项目的总价。在列表框中,我有项目类型和ts价格。我想看到当我向组合框中添加每个项目(单击addButton)时,总价格会增加。但我看到的是,项目被添加到组合框中,但我只看到单个项目的价格,而不是价格的总和。这是我的代码示例 private void addButton_Click(object sender, EventArgs e) { decimal price; // variables to holds the price

我试图在从列表框将项目添加到组合框后计算项目的总价。在列表框中,我有项目类型和ts价格。我想看到当我向组合框中添加每个项目(单击addButton)时,总价格会增加。但我看到的是,项目被添加到组合框中,但我只看到单个项目的价格,而不是价格的总和。这是我的代码示例

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");
    }  
private void addButton\u单击(对象发送者,事件参数e)
{
十进制价格;//保存价格的变量
decimal total=0;//保存总数的变量
整数计数器;
对于(计数器=0;计数器变化:

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");
          }
private void addButton\u单击(对象发送者,事件参数e)
{
十进制价格;//保存价格的变量
decimal total=0;//保存总数的变量
整数计数器;
对于(计数器=0;计数器变化:

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");
          }
private void addButton\u单击(对象发送者,事件参数e)
{
十进制价格;//保存价格的变量
decimal total=0;//保存总数的变量
整数计数器;

对于(计数器=0;如果添加4个项目,计数器是否显示总数(当前)只添加了最后一个?是的,它只显示最后一个。如果您发布与您给出的描述相关的代码,将更容易提供帮助。您可以解释列表框和组合框,然后发布处理一些标签的代码。此外,请修复缩进。在每次单击中,您将总数初始化回0,并仅添加最后一个要了解更多信息-如果添加4项,是否显示总数(当前)只添加了最后一个?是的,它只显示最后一个。如果您发布与您给出的描述相关的代码,将更容易提供帮助。您可以解释列表框和组合框,然后发布处理一些标签的代码。此外,请修复缩进。在每次单击中,您将总数初始化回0,并仅添加最后一个要了解更多-我没有对你的问题投票,但你可以做以下几点:(1)修正缩进,(2)解释为什么将变量
total
移到函数外部可以解决问题。我相信这就是为什么你会投反对票。还有另一种方法:从函数开头的
costLabel
中获取当前的总值,这样你就没有外部变量了。反馈很好-谢谢@Rafalon和FCin。我已经做了根据您的评论进行一些更改。再次感谢!我没有对您的问题进行投票,但您可以做以下操作:(1)修复缩进,(2)解释为什么将变量
total
移到函数外部可以解决问题。我相信这就是为什么你会投反对票。还有另一种方法:从函数开头的
costLabel
中获取当前的总值,这样你就没有外部变量了。反馈很好-谢谢@Rafalon和FCin。我已经做了根据您的评论进行一些更改。再次感谢!