Articles → ADO.NET → Merge 2 Data Tables In Ado.Net
Merge 2 Data Tables In Ado.Net
Example
using System;
using System.Data;
namespace DataTableMerge
{
class Program
{
static void Main(string[] args)
{
// Create the first DataTable
DataTable table1 = new DataTable("Table1");
table1.Columns.Add("ID", typeof(int));
table1.Columns.Add("Name", typeof(string));
table1.Rows.Add(1, "John");
table1.Rows.Add(2, "Jane");
// Create the second DataTable
DataTable table2 = new DataTable("Table2");
table2.Columns.Add("ID", typeof(int));
table2.Columns.Add("Name", typeof(string));
table2.Rows.Add(3, "Peter");
table2.Rows.Add(4, "Susan");
// Create the third DataTable
DataTable table3 = new DataTable("Table3");
table3.Columns.Add("ID", typeof(int));
table3.Columns.Add("Name", typeof(string));
table3.Rows.Add(5, "Mark");
table3.Rows.Add(6, "Lucy");
// Merging DataTable 2 into DataTable 1
table1.Merge(table2);
// Merging DataTable 3 into DataTable 1
table1.Merge(table3);
// Display merged table
Console.WriteLine("Merged DataTable:");
foreach (DataRow row in table1.Rows)
{
Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}");
}
Console.ReadLine();
}
}
}
Output