In this tutorial I will show you how to merge different DataTable in one DataTable.
Suppose you have 2 DataTable
DataTable 1
DataTable 2
Now after merging the two datatable you want the result to be like this.
Suppose you have 2 DataTable
DataTable 1
Hcode | Description |
---|---|
BH01 | Hierarchy 1 |
BH02 | Hierarchy 2 |
DataTable 2
LinesID | LineName | Sequence |
---|---|---|
L01 | Company | 1 |
L02 | Group | 10 |
L03 | Department | 4 |
Now after merging the two datatable you want the result to be like this.
Hcode | Description | LinesID | LineName | Sequence |
---|---|---|---|---|
BH01 | Hierarchy 1 | L01 | Company | 1 |
BH02 | Hierarchy 2 | L02 | Group | 10 |
L03 | Department | 4 |
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.