5.1. Copying Rows from One DataTable to Another
Problem
You have records in a
DataTable that you
need to copy to another DataTable.
Solution
Use the ImportRow( )
method of the DataTable
to copy DataRow objects from one
DataTable to another. Three techniques for
selecting records to copy are demonstrated in the following example:
Use the
Rowsproperty to access rows in theDataRowCollectionof theDataTableusing the row index.Use the
Select( )method of theDataTable.Use the
RowFilterproperty of aDataViewfor theDataTable.
The sample code creates a source DataTable
containing the Orders table from Northwind. A second empty target
DataTable is created with the same schema. One of
the three techniques, as specified by the user, is used to copy
records from the source table to the target table.
The C# code is shown in Example 5-1.
Example 5-1. File: CopyRowsBetweenTablesForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; // Field name constants private const String ORDERID_FIELD = "OrderID"; // . . . // Fill the source table with schema and data. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable dt = new DataTable(ORDERS_TABLE); da.FillSchema(dt, SchemaType.Source); da.Fill(dt); // Clone the schema to the copy table. DataTable dtCopy = dt.Clone( ); if(rowRadioButton.Checked) ...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