Collection was modified; enumeration operation may not execute
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 开发者_如何学Cboolean, 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.
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
?
精彩评论