5.2. Copying Tables from One DataSet to Another
Problem
You need to copy an existing schema and data
from one DataSet
to
another.
Solution
Use one of the following techniques:
Use the
Copy( )
method of theDataTable
when all of the data for a table needs to be copied.Use the
Clone( )
method of theDataTable
to create the schema for each table in the destinationDataSet
when only a subset of the data needs to be copied. You can use theImportRows( )
method of theDataTable
to copy the subset of rows from the source to the destination table.
Once the destination tables are created and the data is copied into
them, the example shows how to create the
DataRelation
objects from the source
DataSet
in the destination
DataSet
.
The sample code contains two event handlers:
Form.Load
Sets up the sample by creating a
DataSet
containing the Orders and Order Details tables from Northwind and a relation between the two tables. The default view for the Orders table is bound to a data grid on the form.- Copy
Button.Click
Creates a destination
DataSet
and copies the schema and specified data into it from the sourceDataSet
created in theForm.Load
event handler.
The C# code is shown in Example 5-2.
Example 5-2. File: CopyTablesBetweenDataSetsForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; private const String ORDERDETAILS_TABLE ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.