Search the articles  
  

• Delete Rows from DataTable And reindex collection

Thursday, August 20, 2009

When you loop through a DataTable object in order to find the match records and delete the rows, it can generally be achieved as below.

foreach (DataRow dr in oDataTable.Rows)
{
   if(dr["Name"]) == "ChristopherThant")
   dr.Delete();
}

However, after you've called the Delete() method from DataRow object, the index in DataRow collection was changed and it makes your looping breaks and thrown an error.

Collection was modified; enumeration operation might not execute.

Some people suggest to commit the DELETE transaction out of the loop by calling AcceptChanges() method.

foreach (DataRow dr in oDataTable.Rows)
{
   if(dr["Name"]) == "ChristopherThant")
   dr.Delete();
}
oDataTable.AcceptChanges();

After I have tried all the possible methods, I finally come up with the decent solution which I've been using whenever I encounter into this situation.

Basically, you will need a method to repopulate the collection index of DataRow.


//With the DataRow[] ToArray(DataRowCollection collection) create a collection-object of datarows and so make sure that there won't be any errors
public static DataRow[] ToArray(DataRowCollection collection)
{
   DataRow[] result = new DataRow[collection.Count];
   collection.CopyTo(result, 0);
   return result;
}

And just apply that method to your DataRow Collection.
foreach (DataRow dr in ToArray(oDataTable.Rows))
{
   if(dr["Name"]) == "ChristopherThant")
   dr.Delete();
}

3 comments:

Anonymous said...

Another way of doing it is like so - this might be more efficient if you are only deleting a small number of item and your collection is large:

List itemsToDelete = new List();
foreach (DataRow dr in dataTable.Rows)
{
if(dr["Name"]) == "ChristopherThant")
itemsToDelete.Add(dr);
}


// Do the removal using iteration over the temp collection
foreach (DataRow dr in itemsToDelete)
{
dataTable.Remove(dr);
}

// Or, do the removal using LINQ, (more concise)...
// itemsToDelete.ForEach(p => dataTable.Remove(p));

Anonymous said...

erp, type, should have been....
List itemsToDelete = new List();

Anonymous said...

ahhh, &GT; and < are removed from postings!

Post a Comment