DataTable already belongs to another DataSet

kbvishnu picture kbvishnu · Jan 12, 2012 · Viewed 79.7k times · Source

This error is occuring while adding one datatable from a dataset to another ."DataTable already belongs to another DataSet."

dsformulaValues.Tables.Add(m_DataAccess.GetFormulaValues
(dv.ToTable.DefaultView.ToTable(False, strSelectedCols)).Tables(0))

Answer

Jay Riggs picture Jay Riggs · Jan 12, 2012

Like the other responses point out, the error you're seeing is because the DataTable you're attempting to add to a DataSet is already a part of a different DataSet.

One solution is to Copy the DataTable and assign the copy to the other DataSet.

dtCopy = dataTable.Copy()
ds.Tables.Add(dtCopy)

The copied DataTable will have the structure and data of the copied DataTable.

If you only want the structure of the DataTable, call Clone instead.

dtCopy = dataTable.Clone()