Collection was modified; enumeration operation may not execute


Self-loop

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)
                                        myList.Add(1)
                                        myList.Add(2)
                                        myList.Add(3)
                                        myList.Add(4)
                                        myList.Add(5)
                                        For Each i As Integer In myList
                                            myList.Remove(i)
                                        Next

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
                                            myList.Remove(i)
                                        Next

4 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.Delete();
    dt.AcceptChanges();
    }
    }
    //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)
    {
    deleteTempContacts(DataGrid1.Items[row].Cells[0].Text);
    }
    row++;
    }
    }

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: