Copying DataSet Contents

You can create a copy of a DataSet so that you can work with data without affecting the original data, or so you can work with a subset of the data from a DataSet. When copying a DataSet, you can:

  • Create an exact copy of the DataSet, including the schema, data, row state information, and row versions.
  • Create a DataSet that contains the schema of an existing DataSet, but only rows that have been modified. You can return all rows that have been modified, or specify a specific DataRowState. For more information about row states, see Row States and Row Versions.
  • Copy the schema, or relational structure, of the DataSet only, without copying any rows. Rows can be imported into an existing DataTable using ImportRow.

To create an exact copy of the DataSet that includes both schema and data, use the Copy method of the DataSet. The following code example shows how to create an exact copy of the DataSet.

Dim copyDS As DataSet = custDS.Copy()
[C#]
DataSet copyDS = custDS.Copy();

To create a copy of a DataSet that includes schema and only the data representing Added, Modified, or Deleted rows, use the GetChanges method of the DataSet. You can also use GetChanges to return only rows with a specified row state by passing a DataRowState value when calling GetChanges. The following code example shows how to pass a DataRowState when calling GetChanges.

' Copy all changes.
Dim changeDS As DataSet = custDS.GetChanges()
' Copy only new rows.
Dim addedDS As DataSet = custDS.GetChanges(DataRowState.Added)
[C#]
// Copy all changes.
DataSet changeDS = custDS.GetChanges();
// Copy only new rows.
DataSet addedDS = custDS.GetChanges(DataRowState.Added);

To create a copy of a DataSet that only includes schema, use the Clone method of the DataSet. You can also add existing rows to the cloned DataSet using the ImportRow method of the DataTable. ImportRow will add data, row state, and row version information to the specified table. Column values will only be added where the column name matches and the data type is compatible.

The following code example creates a clone of a DataSet, then adds the rows from the original DataSet to the Customers table in the DataSet clone for customers where the Country column has the value "Germany".

Dim custGermanyDS As DataSet = custDS.Clone()

Dim copyRows() As DataRow = custDS.Tables("Customers").Select("Country = 'Germany'")

Dim custTable As DataTable = custGermanyDS.Tables("Customers")
Dim copyRow As DataRow

For Each copyRow In copyRows
  custTable.ImportRow(copyRow)
Next
[C#]
DataSet custGermanyDS = custDS.Clone();

DataRow[] copyRows = custDS.Tables["Customers"].Select("Country = 'Germany'");

DataTable custTable = custGermanyDS.Tables["Customers"];

foreach (DataRow copyRow in copyRows)
  custTable.ImportRow(copyRow);

See Also

Creating and Using DataSets | DataSet Class | DataTable Class