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 theDataTablewhen all of the data for a table needs to be copied.Use the
Clone( )method of theDataTableto create the schema for each table in the destinationDataSetwhen only a subset of the data needs to be copied. You can use theImportRows( )method of theDataTableto 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.LoadSets up the sample by creating a
DataSetcontaining 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
DataSetand copies the schema and specified data into it from the sourceDataSetcreated in theForm.Loadevent 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access