collection was modified enumeration operation might not execute

asp.net, c#

Solution

You cannot modify a collection in a `foreach`. Try this as an alternative to apomene's answer (Pretty much does the same thing, except using the remove method of a list instead of indexes.

List<DataRow> toDelete = new List<DataRow>();

foreach(DataRow dr in dt.Rows){
    if(dr["Degree"].ToString() == field){
        toDelete.Add(dr);
    }
}

foreach (DataRow dr in toDelete){
    dt.Rows.Remove(dr);
}

This should solve your problem.

Problem

``` string field = ViewState["Field"].ToString(); DataTable dt = (DataTable)Session["Academic"]; foreach (DataRow dr in dt.Rows) { if (dr["Degree"].ToString() == field) { dr.Delete(); dt.AcceptChanges(); } } Session["Academic"] = dt; gdvwAcademic1.DataSource = Session["Academic"] as DataTable; gdvwAcademic1.DataBind(); ``` when this code executed raise error as "collection was modified enumeration operation might not execute." why this so..?

Original source

Related problems