从数据表中删除列C#

时间:2017-11-01 11:53:39

标签: c# database excel datatable

我目前正在将上传的Excel文档中的字段映射到数据表。我希望删除未选择的列,但它们仍会显示。

这是我的代码:

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);
                }
            }

1 个答案:

答案 0 :(得分:4)

   DataTable t;
   t.Columns.Remove("columnName");
   t.Columns.RemoveAt(columnIndex);