2014-02-16 21 views
0

我在從列表視圖中刪除項目時遇到問題。該程序計算列表中剩餘值的總值。問題是,當我刪除一個項目時,它刪除了在列表視圖中添加的第一個項目的值。在列表視圖中刪除項目和值

例如:

/*I added this items in order. 

item1 = 20, 
item2 = 10, 
item3 = 5 

When I remove item2 its rtbTcost is 15 based on the program below. 
Which means that the value of item1 was removed.*/ 

       int totalRemoved = 0; 


       for (int i = 0; i < lvCart.SelectedItems.Count; i++) 
       { 
        totalRemoved += int.Parse(lvCart.Items[i].SubItems[1].Text); 
        lvCart.Items.Remove(lvCart.SelectedItems[i]); 

       } 

       _listTotal -= totalRemoved; 
       rtbTcost.Text = _listTotal.ToString(); 

回答

0

1啓動和倒計時。

for (int i = lvCart.SelectedItems.Count - 1; i >= 0; i--) 
{ 
     ListViewItem itm = lvCart.SelectedItems[i]; 
     lvCart.Items[i].Remove(); 
} 

總除去

lvCart.SelectedItems.Count 

如果您正在使用從列表視圖中選擇的項目,如要刪除的項目。

刪除後的總和,通過對列中的值求和。

int _listTotal = 0; 
foreach (ListViewItem li in lvCart) { 
    _listTotal += int.Parse(li.Subitems[1].Text); 
} 
rtbTcost.Text = _listTotal.ToString(); 
相關問題