Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable already belongs to another DataSet

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))
like image 945
kbvishnu Avatar asked Jan 12 '12 06:01

kbvishnu


3 Answers

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()
like image 197
Jay Riggs Avatar answered Nov 11 '22 22:11

Jay Riggs


The accepted answer isn't very good. Cloning should always be a last option.

Here's a way around the problem without incurring the overhead of cloning.

        DataSet ds = GetData1();

        DataSet ds2 = GetData2();

        //Assuming you know you've got good data

            DataTable dt = ds2.Tables[0];
            ds2.Tables.Remove(dt);
            dt.TableName = "PortedTable";//you may need to change the table name to prevent conflicts
            ds.Tables.Add(dt);
like image 41
Nathaniel Layton Avatar answered Nov 11 '22 22:11

Nathaniel Layton


Try calling this method:

DataTable dt = dv.ToTable.DefaultView.ToTable(False, strSelectedCols)).Tables(0).Clone()

This will create a copy of the DataTable and assign it to the target DataSet:

ds.Tables.Add(dt)

like image 2
Abbas Avatar answered Nov 11 '22 21:11

Abbas