15

I have a data table and I want to delete a row here is my code it's throwing me an exception

foreach (DataRow row in dt1.Rows)
{
    if ((row["Name"] == "Select a Lookbook") || (row["Name"] == "Create a new Lookbook"))
    {
        row.Delete();
        dt1.AcceptChanges();
    }
}

I even tried outside the if statment and outside forloop still throws me error any idea how to achieve this task this is the exception I get:

Collection was modified; enumeration operation might not execute.

Final working Code:

foreach (DataRow row in dt1.Select())
{
    if ((row["Name"] == "Select a Lookbook") ||    (row["Name"] == "Create a new Lookbook"))
    {
        row.Delete();                                       
    }

}
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
Developer
  • 2,987
  • 10
  • 40
  • 51
  • 1
    possible duplicate of [Safely Removing DataRow In ForEach](http://stackoverflow.com/questions/2341580/safely-removing-datarow-in-foreach) – ChrisF Jun 30 '10 at 14:32

3 Answers3

22

Instead of using dt1.Rows, use dt1.Select()

The goal here is not to use the collection itself, but rather an array of row that is not the Rows collection

Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101
9

Create a list of rows to delete while iterating over DataTable.Rows, then delete them all separately.

Non-LINQ solution:

List<DataRow> rowsToDelete = new List<DataRow>();
foreach (DataRow row in dt1.Rows)
{
    if ((row["Name"] == "Select a Lookbook") || 
        (row["Name"] == "Create a new Lookbook"))
    {
        rowsToDelete.Add(row);
    }
}
foreach (DataRow row in rowsToDelete)
{
    row.Delete();
}
dt1.AcceptChanges();

LINQ solution:

List<DataRow> rowsToDelete = dt1.Rows.AsEnumerable()
    .Where(row => (row["Name"] == "Select a Lookbook") || 
                  (row["Name"] == "Create a new Lookbook"))
    .Tolist();
foreach (DataRow row in rowsToDelete)
{
    row.Delete();
}
dt1.AcceptChanges();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I know it's a very good answer but I have to go with Pierre's answer as I believe easy does it. I really appreciate your help. – Developer Jun 30 '10 at 14:41
1

This is how I did it when I ran into this issue.

            Dim index As Integer = 0
            Dim count As Integer = resultsDT.Rows.Count - 1
            For i As Integer = 0 To count
                If resultsDT.Rows(index).Item("something") = "something" Then
                    resultsDT.Rows(index).Delete()
                    resultsDT.AcceptChanges()
                    index = index - 1
                End If

                index = index + 1
                i = i + 1
            Next
Jordan
  • 11
  • 1