0

I'm enumerating through a Dictionary and creating an item to be added to a ListView. However, one line in particular is causing this error:

Collection was modified; enumeration operation may not execute.

foreach (KeyValuePair<string, bool> s in test.Value.Properties) { ListViewItem item = new ListViewItem(); item.Text = String.Format("{0}", s.Key); if (s.Value) { item.Checked = true; } // the problem line listView2.Items.Add(item); } 

I assume the reason why setting the item.Text works is because I'm not modifying the original value since it's creating a new string. If I change item.Checked = true to create a new boolean, it works fine but the boolean is always defaulted to false which is not what I want.

How can I work around this problem?

Also, should I not be trying to modify any collection's data in a foreach? I originally thought the issue was because I was modifying the collection's data that I'm looping through, but this seems to be an issue with the ListViewItemCollection, which I'm not looping through.

0

1 Answer 1

7

This error is only raised if you modify the collection you are enumerating through.
I can't see anything like that in your code, so there must be some other problem.
I can only guess, but maybe, you modify test.Value.Properties in an event that is raised when you add a new item to the listView2?

Sign up to request clarification or add additional context in comments.

2 Comments

This was the answer I was writing. The OP is making no changes to s or to test.Value.Properties, which is the usual culprit for this type of exception.
Ah, that's it. I had an ItemCheck method on listView2 that's modifying the collection I'm looping through. Haven't found a solution but at least I found the culprit. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.