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.
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)
You could manage a list of indexes to remove and then remove the range.
What is your collection source type bound to your ListView?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With