• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

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

0
YZlat
Asked:
YZlat
  • 3
  • 2
1 Solution
 
AndyAinscowFreelance programmer / ConsultantCommented:
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.
0
 
YZlatAuthor Commented:
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
0
 
YZlatAuthor Commented:
Got it!

  foreach (DataRow drow in rows)
                                dt.Rows.Remove(drow);

worked for me
0
 
AndyAinscowFreelance programmer / ConsultantCommented:
Sneaky - removing from the original collection instead of the intermediate collection you foreach through.
0
 
YZlatAuthor Commented:
solved my own issue
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now