SeeSharp

Hi all,

Suppose we have 5 items in the ListView: "Alpha", "Bravo", "Charlie", "Delta" and "Echo". When we execute RemoveAt(0) followed by another RemoveAt(0), the first two items got removed. If we execute RemoveAt(0) followed by RemoveAt(1), "Alpha" and "Charlie" got removed.

What I want to achieve is: I can multi-select items in the ListView to decide which items i'd like to delete. For example, I select "Alpha" and "Delta", so the index 0 and 3 are stored in SelectedIndexCollection. Then I enumerate this collection to delete these two in one run. At this time, if I run RemoveAt(0) first, the index of "Delta" will be changed to 2.

Can I delete multiple items "at the same time" in the collection without having to mess with the indices



Re: Windows Forms General Removing multiple items in a ListView "at the same time"

nobugz

Classic trick, iterate backwards:

for (int ix = listView1.SelectedIndices.Count-1; ix >= 0; --ix)
listView1.Items.RemoveAt(listView1.SelectedIndices[ix]);

These would be easier though, ListView is smart enough to make this work:

foreach (ListViewItem item in listView1.SelectedItems)
listView1.Items.Remove(item);