1
Reply

deleting rows from Datatable causes error

Philip

Philip

10 years ago
1.2k
I am trying to remove rows that are not needed from a DataTable. Basically, there may be several rows where the itemID is identical. I want to find the rows where the column "failEmail" = "fail", and using the itemID of those rows, remove all rows from the emails DataTable that have the same itemID.
the issue is that only a couple of rows will initially have fail, I need to get the itemID of those ones, and then select all the rows in the emails datatable having that emailID, and delete them
Here is what I have tried:

System.Diagnostics.Debug.Print(emails.Rows.Count.ToString() + " emails!");

// create a list of the email IDs for records that will be deleted

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

foreach (DataRow dr in emails.Rows) {

if (dr["failEmail"].ToString().ToLower() == "fail") {

rows2Delete.Add(dr);

}

}


foreach (DataRow row in rows2Delete) {

DataRow[] drRowsToCheck =emails.Select("itemID ='" + row["itemID"].ToString() +"'");


foreach (DataRow drCheck in drRowsToCheck) {

emails.Rows.RemovedDrCheck);

emails.AcceptChanges();

}

}


Here is the error message I am getting on the second pass:

This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row

How can I do what I need to without throwing errors like that? Is there a better way like using a LiNQ query?




Answers (1)