Link to home
Start Free TrialLog in
Avatar of linkcube1
linkcube1

asked on

Total in a ListView

In the code below I have a Total variable that calculates a total from items in a listview. My problems is when items are deleted the total isn't calculated properly. It seems the total gets changed during deletion by removing the top item off the listview and I am looking to delete the item of the selected index in the listView. So If i add  3 items of (in price) 2.00 3.00 and 5.00 and delete the 3.00 it should return 7.00 while now it returns 5.00. I am not sure how to correct this so any help would be great thanks.
private void btnAddToReceipt_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    ListViewItem newItem = (ListViewItem)item.Clone();
                    listView2.Items.Add(newItem);
                    txtTotal.Refresh();
                    currentTotal = ((MemberBook)newItem.Tag).Price;
                }
                total = total + currentTotal;
                txtTotal.Text = "$ "  + total.ToString();
            }
        }
        
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (listView2.SelectedItems.Count > 0)
            {
                for (int i = listView2.SelectedItems.Count; i > 0; i--)
                {
                    listView2.Items.Remove(listView2.SelectedItems[i - 1]);
                    
                    //total = total - currentTotal;
                    //txtTotal.Text = "$ " + total.ToString();
                }
                total = total - currentTotal;
                txtTotal.Text = "$ " + total.ToString();
            }
        }

Open in new window

Avatar of Carlos Villegas
Carlos Villegas
Flag of United States of America image

Hi, just use this code when you want to recalculate the total:
private void CalculateTotal()
{
    decimal total = 0;
    foreach (ListViewItem item in listView1.Items)
    {
        total += ((MemberBook)item.Tag).Price;
    }
    txtTotal.Text = total.ToString("C");
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Carlos Villegas
Carlos Villegas
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of linkcube1
linkcube1

ASKER

ok thanks for the tips guys!
Glad to help!
and nice advice jdavistx!