Reputation: 879
I am trying to remove all items from a ListViewGroup in a ListView component (C# .NET 4.0). I've tried the following things, but they return unexpected behavioral.
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.
I am now using listView1.Items.Clear();
to clear all items in the group, and readd them one by one. However this causes my GUI to flicker when this action is performed. I'd like to know how to delete all items in a group. So that I only have to re-add the items group (which I want because the number of items vary and name and subitems vary as well).
Note: The group is called lvgChannels
and has index 4.
Upvotes: 0
Views: 2678
Reputation: 1237
what you need is to remove the items from the list view itself for all the items listed inside that group.
for (int i = listView1.Groups[4].Items.Count; i > 0; i--)
{
listView1.Items.Remove(listView1.Groups[4].Items[i-1]);
}
The issue with your code was that you are doing a increment rather than decrement. Every time an item is removed the count decrement, therefore the for loop should start from the maximum count and decrement to 0.
Upvotes: 1
Reputation: 8089
Try this:
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);
}
}
The problem with your second statement is that you remove an item from the list you are iterating over.
Upvotes: 1