DataTable

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have a datatable filled, and i would like to delete one column completely,
but when i use the method Remove(DataColumn column)

i get this error:

Collection was modified; enumeration operation may not execute

Why im getting this error?, i know that im modifing the collection, but this
is the thing that i want to do...
 
It's probably because you are trying to do this inside a foreach loop.
A collection cannot be changed while it's being enumerated.

You can overcome this by iterating over the the columns inside a for
loop instead of a foreach loop, like so:

for ( int i = 0; i < myTable.Columns.Count; ++i )
{
if ( myTable.Coulmns == /* some condition or another */ )
myTable.Columns.RemoveAt(i);
}

That should work fine.
 
This wouldn't work actually. Because as you are removing columns, their
order in the collection changes. Eventually you will get an index out of
range exception.

The for loop needs to count down backwards.
 
Marina, you completely correct. I apologize for the oversight. Here's
the corrected version.

for ( int i = 0; i < myTable.Columns.Count; ++i )
{
if ( myTable.Coulmns == /* some condition or another */ )
myTable.Columns.RemoveAt(i--);
}
 
Hi, Mohammad and Marina, Thanks a lot...

I will try it.

Thanks Again
Kind Regards.
Josema.
 

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

Back
Top