Q: Removing selected items from a ListView?

  • Thread starter Thread starter Visual Systems AB \(Martin Arvidsson\)
  • Start date Start date
V

Visual Systems AB \(Martin Arvidsson\)

Hi!

I'v been struggeling with removing selected items from a listview.

Anyone that can give me a piece of code that does this?

I am a newbee to this C# and cant figure it out....

Regards
Martin Arvidsson
 
This should do the trick. It just loops through the ListView controls
SelectedItems collection and passes that item to its Remove method.

foreach(System.Windows.Forms.ListViewItem eachItem in
this.listView1.SelectedItems)
{
this.listView1.Items.Remove(eachItem);
}
 
Hi,

Well, The below code does work for a DataTable, I bet it will work for a
listview as you will have the exact same issues.

The problem is that you cannot do this:
foreach(ListViewItem item in listview.SelectedItem)
listview.Items.Delete( item );


cause you are modifying the collection and iterating at the same time ( an
exception will be throw IIRC ).

Solution:
Use a temp list
ArrayList elems = new ArrayList()
foreach(ListViewItem item in listview.SelectedItem)
elems.Add( item );

foreach(ListViewItem item in elems)
listview.Items.Delete( item );




Cheers,
 
Hi,

IMO this will not work, you are modifying a collection at the same time you
are iterating it. if you delete an item then that item is not longer
selected so the collection change and the iteration fails


cheers,
 
...
ArrayList elems = new ArrayList()
foreach(ListViewItem item in listview.SelectedItem)
elems.Add( item );

It seems overkill to iterate through the items to copy the references to
another list. Shouldn't this work just as well?

ArrayList elems =
new ArrayList( listview.SelectedItems );

foreach(ListViewItem item in elems)
listview.Items.Delete( item );


// Bjorn A
 
It works fine, SelectedItems is a seperate collection. It does not
remove the item from the SelectedItems collection, it removes it from
the Items collection.
 
Hi ,

It should be the same, only that it's the constructor of ArrayList where
the iteration occurs

cheers,
 
Hi,

Yes, but I bet that the selectedItem collection is modified depending of
the Items collection, there should be a method in ListView that hook in the
Add/Delete, etc events of Items, when It does change it will most probably
recreate the Selected collection iterating in the Items collection and
checking for the Selected property.

Again, I have not tested this, a simple test shoudl say if the above is
correct or not, It does happens with a DataTable / DataView , beside the
above algorithm makes perfectly sense.


Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top