Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy datatable as columns in another datatable

Tags:

c#

datatable

I have a couple of DataTable's and I need to copy them into another DataTable. For example, as you can see in the attached picture, I need to take all the data from the Source Table 1 and copy it in the first 2 columns of the Dest Table, copy Source Table 2 in the next 2 columns, and so on. How can this be easily achieved?

enter image description here

Edit: I have to read several excel files (I am storing each file in a datatable) and I won't know exactly how many source table I will have, so this has to be done dynamically somehow.

like image 292
Rocshy Avatar asked Jun 04 '13 07:06

Rocshy


People also ask

How to copy one DataTable column to another DataTable in c#?

The simplest way is to clone an existing DataTable, loop through all rows of source DataTable and copy data from column by column and add row to the destination DataTable. The following code does the same: For Each dr As DataRow In sourceTable.

How to copy DataTable structure to another DataTable in c#?

Copy() creates a new DataTable with the same structure and data as the original DataTable. To copy the structure to a new DataTable, but not the data, use Clone().

How do I copy a column from one table to another in C#?

To copy column definitions from one table to another. Open the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design. Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy.


2 Answers

Assuming that your source tables have the same structure you can use Table.Copy() to create your dest table and then copy data in loop:

List<DataTable> sourceTables = getYourSourceTablesMethod();
if (sourceTables.Length>0)
{
    DataTable destTable = sourceTables[0].Copy();  

    for (int i = 1; i < sourceTables; i++) 
    {
       foreach (DataRow drow in sourceTables[i].Rows) 
       destTable.Rows.Add(drow.ItemArray);
    }
}
like image 117
Alex Avatar answered Sep 21 '22 04:09

Alex


You can use Merge method which provided by framework , for usage and extra info see Microsoft Datatable Merge

like image 27
Amir Avatar answered Sep 20 '22 04:09

Amir