簡體   English   中英

如何從ListView組件c#中刪除組中的所有項目

[英]How to delete all items from a group in ListView component c#

我試圖從ListView組件(C#.NET 4.0)中的ListViewGroup中刪除所有項目。 我嘗試過以下的事情,但他們會回歸意想不到的行為。

    listView1.Groups[4].Items.Clear(); // Does only remove the item from the group, 
                                       // but is then placed in a new Default group.

foreach (ListViewItem item in listView1.Groups[4].Items)
{ 
    item.Remove(); 
}
// This throws an error which says that the list is changed.

我現在使用listView1.Items.Clear(); 清除組中的所有項目,並逐個讀取它們。 但是,這會導致我的GUI在執行此操作時閃爍。 我想知道如何刪除組中的所有項目。 所以我只需要重新添加項目組(我想要的,因為項目數量不同,名稱和子項目也不同)。

注意:該組稱為lvgChannels ,索引為4。

嘗試這個:

List<ListViewItem> remove = new List<ListViewItem>();

        foreach (ListViewItem item in listView1.Groups[4].Items)
        {
            remove.Add(item);
        }

        foreach (ListViewItem item in remove)
        {
            listView1.Items.Remove(item);
        }
    }

第二個語句的問題是您從正在迭代的列表中刪除一個項目。

您需要的是從列表視圖中刪除該組中列出的所有項目的項目。

for (int i = listView1.Groups[4].Items.Count; i > 0; i--)
{
    listView1.Items.Remove(listView1.Groups[4].Items[i-1]);
}

您的代碼的問題在於您正在進行增量而不是減量。 每次移除一個項目時,計數遞減,因此for循環應從最大計數開始並遞減到0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM