views:

662

answers:

3

My user is able to select multiple items in a ListView collection that is configured to show details (that is, a list of rows).

What I want to do is add a Delete button that will delete all of the selected items from the ListViewItem collection associated with the ListView.

The collection of selected items is available in ListView.SelectedItems, but ListView.Items doesn't appear to have a single method that lets me delete the entire range. I have to iterate through the range and delete them one by one, which will potentially modify a collection I'm iterating over.

Any hints?

Edit: What I'm basically after is the opposite of AddRange().

+1  A: 

As far as I know, there is no way other than to delete them individually.

Wrap your deletion algorithm in ListView.BeginUpdate() and ListView.EndUpdate() calls. This way you won't get the slowdown of repainting on each delete.

Additionally, if you delete them in reverse order, I believe the underlying structure will have less to do.

Also, if the number of items you are deleting is a significant percentage of the total number of items, you might get more performance by clearing the list and AddRange()ing them back again.

lc
A: 

Perhaps you could try something along the lines of the following:

var ItemsToDelete = ... // wherever you get the collection of items to delete from
var RemainingItems = yourList.FindAll(delegate(ListItem x) {
  return !ItemsToDelete.Contains(x)
});
yourListView.DataSource = RemainingItems;
yourListView.DataBind();

or just assign the remaining items to the existing control, or whatever you prefer.

(edited formatting slightly)

rejj
Thats pretty inefficient. For each item in the listview, you're iterating over the ItemsToDelete collection.
Ray Booysen
+1  A: 

If you have a collecion of your selectedItems, you can simply call remove on each of them instead of iterating over the ListView.

There is a method on ListViewItem called Remove().

ListView listview = <reference to ListView>;
foreach (ListViewItem item in listView.SelectedItems)
{
  item.Remove();
}

This removes the iteration through all the items and only removes your selected items.

Ray Booysen
This worked perfectly. It's the most succinct way I've seen so far; thanks Ray.
Andrew
Sure thing. The cool thing about ListViewItems is that they keep a reference to their ListView, which makes this probably the fastest way to do it and only has one iteration
Ray Booysen
I've wrapped your little snippet into an extension method for `ListView` objects, so I've now got a simple call to `RemoveAllSelectedItems()`.
Andrew
Dang; WMD doesn't work in comments. :-(
Andrew