使用c#删除项目时自动计算列表视图中项目的总值

我使用listview作为购物车。 我需要知道在删除项目时如何重新计算购物车的总价值。

这是我添加到listview的代码;

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); } rtbTcost.Text = value.ToString(); } 

这是我删除项目的代码:

 private void btnRemoveItem_Click(object sender, EventArgs e) { int total = 0; foreach (ListViewItem item in lvCart.Items) { if (lvCart.Items[0].Selected) { lvCart.Items.Remove(lvCart.SelectedItems[0]); total += Convert.ToInt32(item.SubItems[1].Text); } } rtbTcost.Text = total.ToString(); } 

我想重新计算项目被删除的项目的总价值。 我该怎么做?

像这样的东西

在表单级别声明

 private int _listTotal; 

添加 – 我认为你有一些问题,因为你应该在添加项目时添加总数

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

然后在删除时 – 你不想在变异集合上使用任何“for-loops”。 但“while”在突变方面完美无缺

 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 } 

没有测试但应该工作

您无法在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); } } 

解决方案是创建重复列表并更改它:

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