YZlat
asked on
Cannot delete a row from datatable
Somehow I can't figure out why my code does not allow me to delete a row from a datatable.
I have two datatables dt and dt2. I want to loop throught dt2 and delete all the rows from dt where field Field1 equals the field Field2 in dt2.
below is my code that seems to find the records but does not delete them
I have two datatables dt and dt2. I want to loop throught dt2 and delete all the rows from dt where field Field1 equals the field Field2 in dt2.
below is my code that seems to find the records but does not delete them
foreach (DataRow row in dt2.Rows)
{
DataRow[] rows = dt.Select("Field1 ='" + row["Field2"].ToString() + "'");
foreach (DataRow drow in rows)
row.Delete();
}
ASKER
Andy, I changed it to:
but nothing has changed
foreach (DataRow row in dt2.Rows)
{
DataRow[] rows = dt.Select("Field1 ='" + row["Field2"].ToString() + "'");
for(int i=0; i<=rows.Length-1;i++)
rows[i].Delete();}
but nothing has changed
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sneaky - removing from the original collection instead of the intermediate collection you foreach through.
ASKER
solved my own issue
Solution - don't use a foreach loop, use something else such as a simple for loop.