Datatable - Remove column if column name contains "Column" word

Hi Team,

I am in the process where I need to remove the columns which have the column name containing the word “Column”.

For example, I have dtNew with column names (“Name”, “Column Place”, “Animal”,“Column Thing”,“Planet”).
I am using the for each loop to scan through DtNew such that I can remove “Column Place” and “Column Thing” and keep the other columns in my dtNew.

What I tried:

for each col in “dtNew.Column”
message box: col.tostring.trim

(Note:- I was able to get the string value of all the column names)

But when I tried:

For each col in “dtNew.Column”
if (col.tostring.trim.contains(“Column”))
Remove Data Column:- (datatable: dtNew) (ColumnName: col.tostring.trim)

(Note:- I was getting an error:- “For Each: Collection was modified; enumeration operation may not execute.”,)
Note: error is popped up only if I use the remove data column activity.

Please help.

Thanks and Regard,

1 Like


I had a similar issue before, what worked for me, was changing the loop value from dtNew.Columns to dtNew.Clone.Columns. ALso make sure that your loop TypeArgument is set to System.Data.DataColumn.

Then in the “if contains” clause, you have your “Remove Data Column” activity, where the datatable property is your regular dtNew.

Let me know if that works.

1 Like


Works smoothly!.

Thanks buddy!

Glad it worked. Most of the time you cannot iterate through a list or collection of items and modify that list at the same time. So here you are cloning the headers of the original dt, and then iterate on that, while removing the columns from the original, as you go.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.