0

Im currently mapping fields from an uploaded excel document to a data table. I want the columns that are not selected to be removed but they still show.

Here is my code:

if(DT.Columns.IndexOf("First Name") != -1)
                DT.Columns["First Name"].ColumnName = "First NameMap";
            DT.Columns[mapping.FirstNameColumnId].ColumnName = "First Name";

            if (DT.Columns.IndexOf("Last Name") != -1)
                DT.Columns["Last Name"].ColumnName = "Last NameMap";
            DT.Columns[mapping.LastNameColumnId].ColumnName = "Last Name";

            if (DT.Columns.IndexOf("Email Address") != -1)
                DT.Columns["Email Address"].ColumnName = "Email AddressMap";
            DT.Columns[mapping.EmailColumnId].ColumnName = "Email Address";


            int ColumnCounter = 0;
            foreach(DataColumn column in DT.Columns)
            {
                if(ColumnCounter != mapping.FirstNameColumnId && ColumnCounter != mapping.LastNameColumnId && ColumnCounter != mapping.EmailColumnId)
                {
                    DT.Columns.Remove(column);
                }
            }
Smac
  • 391
  • 2
  • 10
  • 28
  • When you step through this code in the debugger, where specifically does it fail? Is that `foreach` loop entered at all? Is the `if` statement therein entered at all? When you call `.Remove()` on the target column, is it removed from that object? – David Nov 01 '17 at 11:56
  • So, what is the question? – SᴇM Nov 01 '17 at 11:56
  • The code isnt failing as such. It goes into the DT.Columns.Remove(column); but all the original columns from the excel sheet are still being displayed. I just want it to show the first name , last name, and email – Smac Nov 01 '17 at 11:58
  • You should beware of modifying the Columns collection within the foreach - to be safe make a copy with .ToList() - https://stackoverflow.com/questions/14413099/changing-collection-inside-foreach – PaulF Nov 01 '17 at 11:58
  • where did you bind your datatable to "excel sheets"? – SᴇM Nov 01 '17 at 12:00
  • 1
    As PaulF said, you should not modify a collection within its own foreach loop. You can use a copy as he says, or use a For loop, but be careful the index will change when an item is removed from the collection. You could also just use a lambda expression to filter the columns to whatever columns you want. – Ricardo Olivo Poletti Nov 01 '17 at 12:06

1 Answers1

6
   DataTable t;
   t.Columns.Remove("columnName");
   t.Columns.RemoveAt(columnIndex);
Sunny Jangid
  • 578
  • 4
  • 19