S.R
S.R

Reputation: 27

How to use for loop to sum items

I am trying to calculate the total price of items after adding them to a combo box from a list box. In the list box I have both the type of item and ts price. I want to see the total price to increase as I add each item (click addButton) to the combo box. But what i am seeing is that the item is added to the combo box but I see only individual item prices instead of the sum of the prices. Here is a sample of my code.

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");
    }  

Any help would be appreciated,

Upvotes: 0

Views: 5366

Answers (1)

mjwills
mjwills

Reputation: 23839

Change:

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");
          }

to:

    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");
        }
    }

The important change here is moving the total variable outside the function. This means that the value is maintained between clicks. If you put it inside the function it is reset to 0 on every click (which is not what you wanted).

Upvotes: 4

Related Questions