March 2008
Intermediate to advanced
982 pages
22h 43m
English
You need to access the data in a DataTable using DataReader mechanisms.
Use the CreateDataReader() method of the DataTable object.
The solution uses a DataAdapter to fill a DataTable with data from the first five rows in the Person.Contact in AdventureWorks. The CreateDataReader() method of the DataTable is used to convert the DataTable to a DataTableReader. The contents of the DataTableReader are output to the console.
The C# code in Program.cs in the project ConvertingDataTableToDataReader is shown in Example 6-5.
Example 6-5. File: Program.cs for ConvertingDataTableToDataReader solution
using System; using System.Data; using System.Data.SqlClient; namespace ConvertingDataTableToDataReader { class Program { static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect = "SELECT TOP 5 ContactID, FirstName, LastName " + "FROM Person.Contact"; // Create a data adapter SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString); // Fill a DataTable using DataAdapter and output to console DataTable dt = new DataTable( ); da.Fill(dt); // Create a DataTableReader DataTableReader dtr = dt.CreateDataReader( ); // Iterate over the rows in the DataTableReader and output // the ID, first name, and last name for each person while (dtr.Read( )) Console.WriteLine("{0}\t{1}, {2}", dtr["ContactID"], dtr["LastName"], dtr["FirstName"]); ...Read now
Unlock full access