Deleting a datarow from a dataset!

  • Thread starter Thread starter DBC User
  • Start date Start date
D

DBC User

I would like to delete a row from a dataset based on a condition. Here
is what I am doing

foreach(row in table1)
{
string key = row[columnname];
foreach(row1 in table2)
{
if (row1[columnname].tostring().equals(key))
row1.delete();
}
}

[I made it simple and please ignore the syntax, I have to code
correct]. right adter I do row1.delete on the next foreach loop of
table2, the program throws an exception saying the collection is
changed. How can I delete a row in table2 based on values from table1?

Thanks in advance.
 
DBC User,

Yes, this is correct. You are not allowed to modify elements of an
enumeration while enumerating through them.

To get around this, use a for loop, and use the indexer on the
collection exposed by the Rows property.

Hope this helps.
 
DBC said:
I would like to delete a row from a dataset based on a condition. Here
is what I am doing

foreach(row in table1)
{
string key = row[columnname];
foreach(row1 in table2)
{
if (row1[columnname].tostring().equals(key))
row1.delete();
}
}

[I made it simple and please ignore the syntax, I have to code
correct]. right adter I do row1.delete on the next foreach loop of
table2, the program throws an exception saying the collection is
changed. How can I delete a row in table2 based on values from table1?

Thanks in advance.

I found the problem. I should have break out of the loop once I found
the key. Now it works.
 
Hi,

Rows is a collection you CANNOT modify any collection while being iterating.

what you can do is keep a reference to the rows you want to delete:

ArrayList todelete = new ArrayList();
foreach(row in table1)
{
string key = row[columnname];
foreach(row1 in table2)
{
if (row1[columnname].tostring().equals(key))
todelete.Add( row1);
}
}
foreach( row in todelete )
table2.Rows.Delete( row)
 
Back
Top