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