2008/10/20

Tips: Merge two DataTables (6/16/2009 updated)

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();

4 comments:

  1. hi
    this 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

    ReplyDelete
  2. Thanks for your article. Very helpful. :)

    ReplyDelete
  3. I 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'

    Is there any other way?

    ReplyDelete
  4. If you use the approach that I provided above, the clientDT will be added to the side of the first table.

    ReplyDelete