简体   繁体   中英

Copy DataTable from one DataSet to another

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?

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.

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);

这应该适合你

X.Tables.Add(Y.Tables[<tablename|index>].Copy());
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM