How to Merge 3 DataTables into Single DataTable In C#
How to Merge 3 DataTables into Single DataTable In C# Windows Application ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Manish Kumar ChoudharyPosted Jan 8, 2015, 6:37 AM
CHAITANYA KIRAN KASANIPosted Jan 8, 2015, 6:11 AM
Vithal WadjePosted Jan 8, 2015, 1:59 AM
http://www.c-sharpcorner.com/UploadFile/0c1bb2/merging-multiple-datatables-into-single-datatable-using-asp/
Manish Kumar ChoudharyPosted Jan 8, 2015, 1:37 AM
Hi CHAITANYA KIRAN KASANI,
do like following example.
using System;
using System.Data;
class Program
{
static void Main()
{
var dt1 = new DataTable();
dt1.Columns.Add("id", typeof(int));
dt1.Rows.Add(1);
dt1.Rows.Add(2);
dt1.Rows.Add(3);
var dt2 = new DataTable();
dt2.Columns.Add("name", typeof(string));
dt2.Rows.Add("muke");
dt2.Rows.Add("mike");
dt2.Rows.Add("joel");
var dtfinal = MergeDataTables(dt1, dt2);
// check it worked
foreach(DataColumn dc in dtfinal.Columns)
{
Console.Write("{0, -6}", dc.ColumnName);
}
Console.WriteLine("\n-----------------------");
foreach(DataRow dr in dtfinal.Rows)
{
Console.WriteLine("{0, -6}{1}", dr["id"], dr["name"]);
}
Console.ReadKey();
}
static DataTable MergeDataTables(DataTable table1, DataTable table2)
{
DataTable table3 = table1.Copy();
foreach(DataColumn dc in table2.Columns)
{
table3.Columns.Add(dc.ColumnName).DataType = dc.DataType;
}
for(int i = 0; i < table3.Rows.Count; i++)
{
foreach(DataColumn dc in table2.Columns)
{
string col = dc.ColumnName;
table3.Rows[i][col] = table2.Rows[i][col];
}
}
return table3;
}
}
Piyush PansuriyaPosted Jan 8, 2015, 1:24 AM
If you have same column in all 3 DataTables Than you can use DataTable.Merge() Method.
Ex:
DataTable tbl1;
DataTable tbl2;
tbl1.Merge(tbl2);
But, if you have different column in all 3 DataTables, then you have to declare one common DataTable containing all columns of all 3 DataTables.
Ex: