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
Rows
property to access rows in theDataRowCollection
of theDataTable
using the row index.Use the
Select( )
method of theDataTable
.Use the
RowFilter
property of aDataView
for 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) ...
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.