Delete rows from DataTable

G

Guest

I need to delete some rows from a DataTable. I am not sure if the folllowing
code is supported:

void DeleteBlankRows(DataTable dt)
{
foreach(DataRow dr in dt.Rows)
{
if(AllFieldsEmpty(dr)) dr.Delete();
}
}

I am wondering if the deletion in middle of foreach will interferer with the
interal enumeration.
 
M

Miha Markic [MVP C#]

Hi,

Neo The One said:
I need to delete some rows from a DataTable. I am not sure if the
folllowing
code is supported:

void DeleteBlankRows(DataTable dt)
{
foreach(DataRow dr in dt.Rows)
{
if(AllFieldsEmpty(dr)) dr.Delete();
}
}

I am wondering if the deletion in middle of foreach will interferer with
the
interal enumeration.

Yes, I wouldn't recommend that approach. The thing is that added rows are
actually removed from the list when Delete is invoked on them.
Instead, do a reverse loop (int i = dt.Rows.Count-1 ... i = 0)
 
W

W.G. Ryan MVP

Neo - as an FYI , keep in mind the distinction is w/ Remove vs. Delete.
Delete doesn't actually remove the rows from the collection ,it simply
changes their Rowstate - HOWEVER, the collection is 'modified' so it will
cause a problem.. Remove on the other hand, takes them from the collection
and as such, will also cause a problem with the foreach syntax. Now, if you
were to call .AccpetChanges in the middle of the foreach loop w/ Delete, it
will take the row out of the collection as well which will cause a problem.
I believe you can get through one pass w/ Delete, but it's definitely not
something you want to do.

So I guess that's a lot of babble I included just to confirm that it will
cause a problem ;-). Anyway, for this operation, I'd just use a for(int i)
loop.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top