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

后端 未结 3 807
旧时难觅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条回答
  •  猫巷女王i
    2021-01-28 23:43

    You can't change the same list in foreach.

    foreach (ListViewItem item in lvCart.Items)
    {
        if (lvCart.Items[0].Selected)
        {
            lvCart.Items.Remove(lvCart.SelectedItems[0]);
            total += Convert.ToInt32(item.SubItems[1].Text);
        }
    }
    

    The solution is create duplicate list and change it:

    var newList = lvCart;
    
    foreach (ListViewItem item in lvCart.Items)
    {
        if (lvCart.Items[0].Selected)
        {
            newList.Items.Remove(lvCart.SelectedItems[0]);
            total += Convert.ToInt32(item.SubItems[1].Text);
        }
    }
    

提交回复
热议问题