Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Table + delete a row in c# using loop

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();                                       
    }

}
like image 398
Developer Avatar asked Jun 30 '10 14:06

Developer


People also ask

How to Delete a row from DataTable?

There are two methods you can use to delete a DataRow object from a DataTable object: the Remove method of the DataRowCollection object, and the Delete method of the DataRow object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion.

How to Delete selected row from DataTable in c# net?

You need a way to delete the row from DataTable directly without iterating thru the Rows collection. DataTable. Rows collection has Remove method which takes an instance of DataRow as a parameter. So if you can get hold of the DataRow to be deleted, then all you need to do is call usersTable.

Why can't I delete a row in a table?

Highlight the row, right-click the row header, and select delete. Alternately, try typing Ctrl minus.


2 Answers

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

like image 74
Pierre-Alain Vigeant Avatar answered Oct 23 '22 12:10

Pierre-Alain Vigeant


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();
like image 29
Jon Skeet Avatar answered Oct 23 '22 12:10

Jon Skeet