Copy DataTable from one DataSet to another

MrCatacroquer picture MrCatacroquer · Feb 4, 2011 · Viewed 93.8k times · Source

I'm trying to add to a new DataSet X a DataTable that is inside of a different DataSet Y. If I add it directly, I get the following error:

DataTable already belongs to another DataSet.

Do I have to clone the DataTable and import all the rows to it and then add the new DataTable to the new DataSet? Is there a better/easy way to do it?

Answer

There are two easy ways to do this:

DataTable.Copy

Instead of DataTable.Clone, use DataTable.Copy to create a copy of your data table; then insert the copy into the target DataSet:

dataSetX.Tables.Add( dataTableFromDataSetY.Copy() );

DataSet.Merge

You could also use DataSet.Merge for this:

dataSetX.Merge(dataTableFromDataSetY);

Note, however, that if you are going to use this method, you might want to make sure that your target DataSet doesn't already contain a table with the same name:

  • If the target DataSet doesn't contain a table by the same name, a fresh copy of the table is created inside the data set;

  • If a table by the same name is already in the target data set, then it will get merged with the one passed to Merge, and you end up with a mix of the two.