How To Merge Records From One DataTable Into Another Datatable


There are certain scenarios where you have data in 2 different data tables and you want to merge the data of these data tables into one of them. In this article, we will see how this can be done using C# in very simple steps. The article assumes that the number of columns are the same in both of the data tables.

The DataTable class of the .Net library provides a very easy method to do it. The method is known as ImportRow(). As the name suggests, this method imports a row from one data table into another data table. To copy all rows from one data table into another, you can use the following code:

  1. DataTable table1 = GetData(); //get Rows in 1st Data Table  
  2. DataTable table2 = GetData(); //get Rows in 2nd Data Table  
  3. foreach (DataRow item in table2.Rows) //Iterate through each row of 2nd data table  
  4. {  
  5.      table1.ImportRow(item); //Import the row in 1st data table  

I hope you like this! Keep learning and sharing! Cheers!