7
 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..?

oɔɯǝɹ
  • 7,219
  • 7
  • 58
  • 69
kls
  • 121
  • 1
  • 2
  • 12
  • Have you seen the duplicates on SO according to this exception? – Tim Schmelter Feb 20 '15 at 10:19
  • possible duplicate of [Collection was modified; enumeration operation may not execute](http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) – Magnus Feb 20 '15 at 10:39

4 Answers4

10

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.

David Watts
  • 2,249
  • 22
  • 33
6

You can't modify the collection in a foreach. So don't delete or add things in it.

You could prevent this error by creating a new collection with items you want to modify, for example with LINQ (the ToList() is essential):

var toDelete = dt.AsEnumerable().Where(r => r["Degree"].ToString() == field).ToList();

Now you can loop this without a problem.

foreach(DataRow rowToDelete in toDelete)
    rowToDelete.Delete();
dt.AcceptChanges(); // you could do that also in the loop now
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

you cant delete inside foreach use for loop or make a delete List:

List <int> toBeDel=new List<int>();

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

 foreach (int i in toBeDel)
 {
     dt.Rows[i].Delete();
 }
apomene
  • 14,282
  • 9
  • 46
  • 72
0
for (int i = 0;i < dt.Rows.Count; i++)
 {
      DataRow dr = dt.Rows[i];
      if (dr["Degree"].ToString() == field)
      {
            dr.Delete();
            i-=1;
      }
 }
dt.AcceptChanges();

you can use this, one loop. For any people find this post.

Ngọc Anh
  • 99
  • 1
  • 6