March 2008
Intermediate to advanced
982 pages
22h 43m
English
You need to access values in a DataTable or DataSet.
Use one of the techniques shown in this solution.
The C# code in Program.cs in the project RetrieveValuesDataTable is shown in Example 3-7.
Example 3-7. File: Program.cs for RetrieveValuesDataTable solution
using System; using System.Data; using System.Data.SqlClient; namespace RetrieveValuesDataTable { 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 14"; // 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); // Accessing rows using indexer Console.WriteLine("---Index loop over DataRowCollection---"); for (int i = 0; i < 5; i++) { DataRow row = dt.Rows[i]; Console.WriteLine("Row = {0}\tContactID = {1}\tFirstName = {2}" + "\tLastName = {3}", i, row[0], row["FirstName"], row[2, DataRowVersion.Default]); } // Accessing rows using foreach loop Console.WriteLine("\n---foreach loop over DataRowCollection---"); int j = 0; foreach (DataRow row in dt.Rows) { j++; Console.WriteLine("Row = {0}\tContactID = {1}\tFirstName = {2}" + "\tLastName = {3}", j, row[0], row["FirstName"], row["LastName", DataRowVersion.Default]); ...Read now
Unlock full access