Tuesday, January 30, 2018

Merge Multiple DataTable into Single DataTable C#

In this tutorial I will show you how to merge different DataTable in one DataTable.

Suppose you have 2 DataTable

DataTable 1

HcodeDescription
BH01Hierarchy 1
BH02Hierarchy 2

DataTable 2

LinesIDLineNameSequence
L01Company1
L02Group10
L03Department4


Now after merging the two datatable you want the result to be like this.

HcodeDescriptionLinesIDLineNameSequence
BH01Hierarchy 1L01Company1
BH02Hierarchy 2L02Group10
L03Department4

To accomplish this structure use the following code


void AddColumns(DataTable dt)
        {

            foreach (DataColumn dc in dt.Columns)
            {
                NewDt.Columns.Add(dc.ColumnName);
            }
        }

        DataTable Merge(DataSet ds)
        {
            int maxRows = 0;
            foreach (DataTable dt in ds.Tables)
            {
                AddColumns(dt);
                if (maxRows < dt.Rows.Count)
                    maxRows = dt.Rows.Count;
            }
            for (int i = 0; i < maxRows; i++)
            {
                DataRow drToAdd = NewDt.NewRow();
                NewDt.Rows.Add(drToAdd);
            }

            int CurrentRow = 0;

            int parentcount = 0;
            foreach (DataTable dt in ds.Tables)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    int colcount = 0;
                    foreach (DataColumn dc in dt.Columns)
                    {
                        NewDt.Rows[CurrentRow][colcount + parentcount] = dr[dc];

                        colcount++;
                    }
                    CurrentRow++;
                }
                CurrentRow = 0;
                parentcount += dt.Columns.Count;
            }
            return NewDt;
        }

Just call the Merge method and pass your DataSet.

The Above code will work on multiple DataTable, so if you have more than 2 Datatable it will just work fine

I hope it was informative for you and I would like to Thank you for reading.

No comments:

Post a Comment