none
Remove All Columns From DataTable After 5th column RRS feed

  • Question

  • Hello - I am allowing users to import an Excel Spreadsheet into a DataTable.  This works, but sometimes the users will import more data then is needed, so to combat such I want to delete everything in the datatable after the 5th column.

    What would be C# logic to delete all columns after column 5 in a datatable?

    Thursday, August 2, 2018 12:40 PM

Answers

  • Try the following.

    var dt = new DataTable();
    dt.Columns.Add(new DataColumn() {ColumnName = "C1"});
    dt.Columns.Add(new DataColumn() { ColumnName = "C2" });
    dt.Columns.Add(new DataColumn() { ColumnName = "C3" });
    dt.Columns.Add(new DataColumn() { ColumnName = "C4" });
    dt.Columns.Add(new DataColumn() { ColumnName = "C5" });
    dt.Columns.Add(new DataColumn() { ColumnName = "C6" });
    dt.Columns.Add(new DataColumn() { ColumnName = "C7" });
    
    Console.WriteLine(dt.Columns.Count);
                 
    while (dt.Columns.Count >5)
    {
        dt.Columns.RemoveAt(dt.Columns.Count -1);
    }
    
    dt.Columns.Cast<DataColumn>().ToList().ForEach(col => Console.WriteLine(col.ColumnName));


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by IndigoMontoya Thursday, August 2, 2018 12:58 PM
    Thursday, August 2, 2018 12:56 PM
    Moderator