Link to home
Start Free TrialLog in
Avatar of YZlat
YZlatFlag for United States of America

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

 foreach (DataRow row in dt2.Rows)
{
       	DataRow[] rows = dt.Select("Field1 ='" + row["Field2"].ToString() + "'"); 
	foreach (DataRow drow in rows) 
        	row.Delete(); 
}

Open in new window

Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Simple - inside a foreach you have the collection as readonly.  (Otherwise it can lose track of where it is).

Solution - don't use a foreach loop, use something else such as a simple for loop.
Avatar of YZlat

ASKER

Andy, I changed it to:

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

Open in new window


but nothing has changed
ASKER CERTIFIED SOLUTION
Avatar of YZlat
YZlat
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sneaky - removing from the original collection instead of the intermediate collection you foreach through.
Avatar of YZlat

ASKER

solved my own issue