25

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?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
MrCatacroquer
  • 2,038
  • 3
  • 16
  • 21

4 Answers4

73

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.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
4

Use this generic function

public DataTable CopyDataTable(DataTable dtSource, int iRowsNeeded)
{

    if (dtSource.Rows.Count > iRowsNeeded)
    {
        // cloned to get the structure of source
        DataTable dtDestination = dtSource.Clone();
        for (int i = 0; i < iRowsNeeded; i++)
        {
            dtDestination.ImportRow(dtSource.Rows[i]);
        }
        return dtDestination;
    }
    else
        return dtSource;
}

Suppose you want to copy first table of sourceSet to destinationSet.
Call it like

DataTable destinationTable = CopyDataTable(sourceSet.Tables[0], sourceSet.Tables[0].Rows.Count);
DataSet destinationSet = new DataSet();
destinationSet.Tables.Add(destinationTable);
naveen
  • 53,448
  • 46
  • 161
  • 251
2

This should work for you

X.Tables.Add(Y.Tables[<tablename|index>].Copy());
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
1
IEnumerable<DataRow> query =  from sourceTbl in sourceTbl.AsEnumerable()
where [any condition you want]
select order;
DataTable boundTable = query.CopyToDataTable<DataRow>();

I am not sure If i understood your question properly.Hope this code helps

RaM
  • 1,126
  • 10
  • 25