使用c#删除项目时自动计算listview中项目的总值

时间:2014-02-15 19:21:39

标签: c# listview

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

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

3 个答案:

答案 0 :(得分:1)

像这样的东西

在表单级别声明

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(<myVal>)...???
    _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

}

未经测试但应该正常工作

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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