How To Merge Two DataTables Into One Using C#

Let's create a project and name it Demo. Write the following code in default.aspx.cs.

  1. DataTable dt = new DataTable("Order");  
  2. DataColumn dc = dt.Columns.Add("ID"typeof(int));  
  3. dt.Columns.Add("Name"typeof(String));  
  4.   
  5. dt.Rows.Add(1, "pramod");  
  6. dt.Rows.Add(2, "ravi");  
  7. dt.Rows.Add(3, "deepak");  
  8. dt.Rows.Add(4, "kiran");  
  9. dt.Rows.Add(5, "madhu")  
Set a breakpoint on line dt.Rows.Add(5,”madhu”) and hit F5. Mouseover on dt and then click on the arrow icon and you will get the following screen.

data table

After clicking on DataTable visualizer you will get this.

Output

table order

Now create another datatable.
  1. DataTable dt2 = new DataTable(“Order”);  
  2. DataColumn dc2 = dt2.Columns.Add(“ID”, typeof(int));  
  3. dt2.Columns.Add(“Name”, typeof(String));  
  4. dt2.Columns.Add(“Type”, typeof(String));  
  5.   
  6. dt2.Rows.Add(6, “ashu”,”Gen”);  
  7. dt2.Rows.Add(7, “rudra”, “Gen”);  
  8. dt2.Rows.Add(8, “kavita”, “Gen”);  
  9. dt2.Rows.Add(9, “suman”, “Gen”);  
  10. dt2.Rows.Add(10, “lakshman”, “Gen”);  
Set a BreakPoint on line dt2.Rows.Add(10, “lakshman”, “Gen”) and hit F5.

Output

dataset viewer
  1. // Add both datatable in single datatable.  
  2. dt.Merge(dt2);  
Output

meagre table

I hope you enjoy this article.

Happy coding.

 


Similar Articles