How to merge two DataTable into one? Here is what I did:
private static DataTable AppendDataTable(DataTable hostDt, DataTable clientDt)
{
if (hostDt != null && hostDt.Rows.Count > 0)
{
DataRow dr;
for (int i = 0; i < clientDt.Columns.Count; i++)
{
hostDt.Columns.Add(new DataColumn(clientDt.Columns[i].ColumnName));
if (clientDt.Rows.Count > 0)
for (int j = 0; j < clientDt.Rows.Count; j++)
{
dr = hostDt.Rows[j];
dr[hostDt.Columns.Count - 1] = clientDt.Rows[j][i];
dr = null;
}
}
}
return hostDt;
}
You don't have to return the hostDt because the reference type object is passed by reference. However, if your source tables will be disposed after merging, you have to replace the return statement by this:
return hostDt.Copy();
hi
ReplyDeletethis is a very gud article but we have 2 use
dt1.Merge(dt2 );
more details..
http://itneeds4u.blogspot.com/2011/01/how-to-merge-two-datatable-and-get.html
Thanks for your article. Very helpful. :)
ReplyDeleteI tried the Merge (DataTable.Merge()), but it is adding the records to bottom of first one, I need it to be added into the side[as columns] to first table'
ReplyDeleteIs there any other way?
If you use the approach that I provided above, the clientDT will be added to the side of the first table.
ReplyDelete