Collection was modified; enumeration operation may not execute
Collection was modified; enumeration operation may not execute
This exception is thrown when you are trying to delete items of a collection in a for loop or using a for each loop.
The ideal solution could be to use a for loop with a descending counter.
Problem:
for e.g.
If suppose you are executing any of following code snippets
1.
for (int listcounter = 0; listcounter < ReferenceOwnersList.Items.Count; listcounter++)
{
ReferenceOwnersList.Items.Delete(0);
}
2.
foreach (SPListItem Li in ReferenceOwnersList.Items)
{
Li.Delete();
}
Here ReferenceOwnersList is a collection.
Now whenever this code will execute for the first time, the number of items reduce. So the second item gets the first index.
I tried deleting 0th item everytime but still I got the exception. Again changing index may cause skipping the items in most senerios.
And the collection throws the “Collection was modified; enumeration operation may not execute” exception.
Solution:
Solution
Use a reducing for loop.
for (int cntLi = ReferenceOwnersList.Items.Count – 1; cntLi >=0 ;cntLi — )
{
ReferenceOwnersList.Items.Delete(cntLi);
}
so that even if the last item is deleted, the index of other items wont change.

Hello, I can’t understand how to add your blog in my rss reader
April 27th, 2009 at 9:12 AM————————
hi,
use following link for my RSS
http://codeforfuture.com/feed/
April 27th, 2009 at 11:44 AMgreat domain name for blog like this)))
April 29th, 2009 at 3:33 AM————————