Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I found this bit challenging.I need to update my datatable headers dynamically for that i have an arraylist of updated headers

var distinctArray = newcolumnsList.ToArray();

I have datatable dTable with old headers and values.I want to replace dTable headers with

distinctArray values.How can do this? (5 old headers remove and add 5 new headers in distinctArray,dynamically )

What I have tried:

var distinctArray = newcolumnsList.ToArray(); // array having new headings.


foreach (string item in distinctArray)
{
dTable[0].Rows.Add(item);
}
return dTable;
}
Posted
Updated 15-Sep-20 20:14pm
v4

1 solution

Here you are an example how to do it.
C#
using System.Collections.Generic;
using System.Data;

namespace DataTableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var dt = new DataTable();

            var dataColumns = new List<DataColumn>
            {
                new DataColumn("A"),
                new DataColumn("B"),
                new DataColumn("C"),
                new DataColumn("D"),
                new DataColumn("E")
            }.ToArray();

            dt.Columns.AddRange(dataColumns);

            dt.Rows.Add(1, 2, 3, 4, 5);

            var newDataColumns = new List<DataColumn>
            {
                new DataColumn("F"),
                new DataColumn("G"),
                new DataColumn("H"),
                new DataColumn("I"),
                new DataColumn("J")
            }.ToArray();

            dt.Columns.Clear();

            dt.Columns.AddRange(newDataColumns);
        }
    }
}


You cannot replace DataColumns directly.
You must first remove the old DataColumns by using the Clear method.
C#
dt.Columns.Clear();

Then you can add a new DataColumn array.
C#
dt.Columns.AddRange(newDataColumns);

A good idea might be to use a debugger to see what is happening after each line of code.
Moreover it is recommended to read this article:
A Practical Guide to .NET DataTables, DataSets and DataGrids - Part 1[^]
 
Share this answer
 
Comments
Maciej Los 16-Sep-20 2:22am    
5ed!
TheRealSteveJudge 16-Sep-20 3:02am    
Thank you, Maciej!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900