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

0 Comments:

Random Posts

Powered by Stuff-a-Blog