2.14. Converting Between a DataTable and a DataRow Array
Problem
You need to convert between a DataTable
object and an array of DataRow
objects.
Solution
Use the CopyTo( )
method of the DataRowCollection
for the DataTable
to convert from a DataTable
to an array of DataRow
objects.
Use the CopyToDataTable( )
method of the DataRow
array to copy elements from a DataRow
array to a DataTable
.
The solution creates and fills a DataTable
from the Person.Contact
table in AdventureWorks
. A DataRow
array is created from the rows in the DataTable
. Two DataTable
objects are created from the DataRow
array using different overloads of the CopyToDataTable( )
method of the DataRow
array. Results are output to the console.
The C# code in Program.cs in the project ConvertBetweenDataTableAndDataRowArray
is shown in Example 2-14.
Example 2-14. File: Program.cs for ConvertBetweenDataTableAndDataRowArray solution
using System; using System.Data; using System.Data.SqlClient; namespace ConvertBetweenDataTableAndDataRowArray { class Program { static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect = "SELECT ContactID, FirstName, LastName FROM Person.Contact " + "WHERE ContactID BETWEEN 10 AND 13"; // Create a data adapter SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString); // Fill a DataTable using DataAdapter DataTable dt1 = new DataTable(); da.Fill(dt1); // Output the rows from the table Console.WriteLine( ...
Get ADO.NET 3.5 Cookbook, 2nd Edition 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.