How to add two datatable in single datatable in C#

In this article we learn how to add two datatable in c#.

Lets create a project and name it Demo. Write following code on default.aspx.cs

DataTable dt = new DataTable("Order");
DataColumn dc = dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(String));

dt.Rows.Add(1, "pramod");
dt.Rows.Add(2, "ravi");
dt.Rows.Add(3, "deepak");
dt.Rows.Add(4, "kiran");
dt.Rows.Add(5, "madhu");

Set a breakpoint on line dt.Rows.Add(5,”madhu”) and hit F5. Mouseover on dt and afterthat click on arrow icon and you will get this screen.

4

After clicking on DataTable visualizer you will get this.

Output

1

Now create an another datatable.

DataTable dt2 = new DataTable("Order");
DataColumn dc2 = dt2.Columns.Add("ID", typeof(int));
dt2.Columns.Add("Name", typeof(String));
dt2.Columns.Add("Type", typeof(String));

dt2.Rows.Add(6, "ashu","Gen");
dt2.Rows.Add(7, "rudra", "Gen");
dt2.Rows.Add(8, "kavita", "Gen");
dt2.Rows.Add(9, "suman", "Gen");
dt2.Rows.Add(10, "lakshman", "Gen");

Set a breakpoint on line dt2.Rows.Add(10, “lakshman”, “Gen”) and hit F5.
Output

2

// Add both datatable in single datatable.
dt.Merge(dt2);

Output

3

I hope you enjoy this article.

Happy coding :)

Tags: , ,