autocalculate total value of items in listview when removing item using c#

后端 未结 3 806
旧时难觅i
旧时难觅i 2021-01-28 23:32

I\'m using a listview as a shopping cart. I need to know how to recalculate the total value of the cart when I remove an item.

Here is my code for adding to listview;

3条回答
  •  佛祖请我去吃肉
    2021-01-29 00:00

    Something like this

    On the form level declare

    private int _listTotal;
    

    Adding - I think here you have some problems because you should add to total when you add the item

    private void btnACart_Click(object sender, EventArgs e)
    {
        int value = 0;
    
        for (int i = 0; i < lvCart.Items.Count; i++)
        {
            value += int.Parse(lvCart.Items[i].SubItems[1].Text);
        }
        // how about lvCart.Items.Add()...???
        _listTotal += value; // and here add myVal
        rtbTcost.Text = _listTotal.ToString();
    }
    

    Then when removing - you don't want to use any "for-loops" on mutating collection. But "while" works perfectly on mutations

    private void btnRemoveItem_Click(object sender, EventArgs e)
    {
        int totalRemoved = 0;
        while (lvCart.SelectedItems.Count > 0)
        {
            totalRemoved += Convert.ToInt32(lvCart.SelectedItems[0].SubItems[1].Text);
            lvCart.Items.Remove(lvCart.SelectedItems[0]);
        } 
        _listTotal -= totalRemoved;
        rtbTcost.Text = _listTotal.ToString
    
    }
    

    Not tested but should work

提交回复
热议问题