使用C#删除项目时autocalculate列表视图中的项目总价值 [英] autocalculate total value of items in listview when removing item using c#
问题描述
我用一个ListView作为一个购物车。我需要知道如何重新计算车的总价值时,我删除项目。
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.
下面是我的code添加到列表视图;
Here is my code for adding to 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();
}
下面是我的code去除项目:
Here is my code for removing items:
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();
}
我要重新计算一个项目被删除的项目的总价值。我应该怎么办呢?
I want to recalculate the total value of items an item is removed. How should I do that?
推荐答案
像这样
在形式层面申报
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();
}
然后在取出时 - 你不希望使用任何for循环上的变异集合。但是,而上的突变完美的作品
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
这篇关于使用C#删除项目时autocalculate列表视图中的项目总价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!