September 13, 2014 by Nitesh

How To Copy Records from One DataTable to 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 post, we will see how this can be achieved using C# in very simple steps. The post assumes that the number of columns are same in both the data tables.

DataTable class of .Net library provides a very easy method to perform this operation. 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 below code –

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

Hope you like this! Keep learning and sharing! Cheers!

#.Net#C##DataTable#How To?

Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup