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

后端 未结 3 804
旧时难觅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-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);
        }
    }
    
    0 讨论(0)
  • 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(<myVal>)...???
        _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

    0 讨论(0)
  • 2021-01-29 00:03
    private void btnRemoveItem_Click(object sender, EventArgs e)
    {
        int total = 0;
        foreach (ListViewItem item in lvCart.Items)
        {
           if (lvCart.Items[0].Selected)
            {
                total+=(int)lvCart.SelectedItems[0].SubItems[1].Text;//Add to total while romving
               lvCart.Items.Remove(lvCart.SelectedItems[0]);
               //total += Convert.ToInt32(item.SubItems[1].Text);
            }
        }
    
          rtbTcost.Text = total.ToString();
       }
    
    0 讨论(0)
提交回复
热议问题