Collection was modified; enumeration operation may not execute


Image via Wikipedia

The error occurs when you are performing a for each loop over a generic list or a collection and there is a line of code inside the loop that is trying to modify the contents of the list. Take a look at the code below :

                                        Dim myList As New List(Of Integer)
                                        For Each i As Integer In myList

the above code will throw an InvalidOperationException because we are removing items from the list while we are still iterating over its items using the for each loop.

a simple fix to the above code would be replacing the for each loop with the standard index loop as follows :

                                      For i As Integer = 0 To myList.Count - 1

5 Responses to Collection was modified; enumeration operation may not execute

  1. msbuzzz says:

    Thanks for this, Now I have got a problem, How can I change this ,

    foreach (DataRow dr in dt.Rows)
    dr[“Comments”] = StripHTML(dr[“Comments”].ToString());
    if (dr[“” + internalClosure + “”].ToString() != null)
    if ((DateTime)dr[“” + internalClosure + “”] <= DateTime.Now)
    //dr["FeedBack"] = "\" " + dr["FeedBack"].ToString() + " \" \n – " + dr["" + internaln + ""].ToString(); for user name

  2. Hello,

    But I’ve a grid with checkbox and I need to delete the selected rows from the grid:

    This is my code, so how can I get the rowindex if I use the for() statement?

    Thanks in advance
    protected void image1_Click(object sender, ImageClickEventArgs e)
    int row=0;
    foreach (DataGridItem di in DataGrid1.Items)
    CheckBox chkBx = di.FindControl(“cbDelete”) as CheckBox ;
    if (chkBx != null && chkBx.Checked)

  3. Pingback: [Exception] Collection was modified; enumeration operation may not execute | 理查' life

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: