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?
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.
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.
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().
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.
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);
}
}
You can use Merge method which provided by framework , for usage and extra info see Microsoft Datatable Merge
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With