Steffen Hvid
Steffen Hvid

Reputation: 187

Removing columns from DataTable

I am trying to delete datacolumns from a datatable: I get the following error:

System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'

when i try to execute the following code:

foreach (DataColumn col in csvData.Columns)
        {
            if (col.ColumnName.Contains("Column"))
            {
                csvData.Columns.Remove(col);
            }
        }

I do understand the error, since i is true that i am modifying the collection. I just don't know how to handle it. Anyone have an idea? I tried rapping it in a try/catch, but that only removes the first column containing column.

Upvotes: 0

Views: 600

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

This code should solve the issue, by using a for loop and go from upperbound to 0

for (int i = csvData.Columns.Count - 1; i >= 0; i--)
{
   DataColumn dc = csvData.Columns[i];
   if (dc.ColumnName.Contains("Column"))
   {
       csvData.Columns.Remove(dc);
   }
}

Upvotes: 1

Related Questions