3.6. Accessing Data Values in a DataTable or DataSet

Problem

You need to access values in a DataTable or DataSet.

Solution

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

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.