Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove multiple selected items from a WPF ListView?

I have a WPF ListView with many items in it. When I select several of them, I want to be able to remove them with a button. The problem I am having is that I can remove ONE item from the ListView, but then when I iterate the second time, I get a:

Collection was modified; enumeration operation may not execute.

Error because of the last removal modifying the ItemSource of that ListView. What is the best way to do this? I tried making a copy of the selected items but I don't know what type to use.

like image 447
joepetrakovich Avatar asked Mar 27 '26 01:03

joepetrakovich


2 Answers

Save the collection of selected items in a local variable that won't change, then you can iterate over that without problems.

e.g.

var selected = lv.SelectedItems.Cast<Object>().ToArray();
foreach (var item in selected) lv.Items.Remove(item); // or whereever you need to remove them...

(Cast<T> and ToArray are extension methods)

like image 70
H.B. Avatar answered Mar 30 '26 01:03

H.B.


You could manage a list of indexes to remove and then remove the range.

What is your collection source type bound to your ListView?

like image 42
SliverNinja - MSFT Avatar answered Mar 30 '26 00:03

SliverNinja - MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!