This error is occuring while adding one datatable from a dataset to another .\"DataTable already belongs to another DataSet.\"
dsformulaValues.Tables.Add(m_D
I guess this means the DataTable belongs to another DataSet...
You can serialze the DataTable to XML, then deserialize it into your target DataSet.
I think u should create a new DataTable and import the struct and data to the new one.
I had the same problem and I solved it using Remove
. In my opinion, your code could be this:
dsformulaValues.Tables.Add(m_DataAccess.GetFormulaValues
(dv.ToTable.DefaultView.ToTable(False, strSelectedCols)).Tables(0))
dsformulaValues.Tables.Remove(//I'm not sure to understand your code, so read this code line as only an input for your stuff. Please, consider my code below for more understanding.
My working code was like this:
DataTable myTable = new DataTable();
private void Save()
{
DataSet myDataSet = new DataSet();
myDataSet.Tables.Add(myTable);
myDataSet.Tables.Remove(myTable);//This works
myDataSet.WriteXml("myTable.xml");
}
private void buttonSave_Click(object sender, EventArgs e)
{
Save();
}
Every time I clicked the button buttonSave
, the message “DataTable already belongs to another DataSet" appeared. After writing the line code myDataSet.Tables.Remove(myTable);//This works
the application started running without problems and now I can click the button more times, without losing the value of myTable
and without the error message.
I hope this can help.
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)
Try to copy the table with DataTable.Copy() method in case it's not a typed DataSet. This method creates a new instance of the same table so it not gonna belong to any DataSet:
dim newTable as DataTable = oldTable.Copy() dim dv as DataView = newTable.DefaultView
dsformulaValues.Tables.Add(m_DataAccess.GetFormulaValues(dv.ToTable.DefaultView.ToTable(False, strSelectedCols)).Tables(0))
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()