O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 the DataRowCollection of the DataTable using the row index.

  • Use the Select( ) method of the DataTable.

  • Use the RowFilter property of a DataView for the DataTable.

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required