Retrieve Values from a DataRow Array using different techniques

Retrieve Values from a DataRow Array using different techniques



In this example we are going to see how to retrieve data values from a DataRow Array using different techniques.

Here we are using five different ways to access the data in a DataRow array:

  1. Using a column ordinal.
  2. Using a column name.
  3. Using the strongly typed accessor Field<T> with a column ordinal.
  4. Using the strongly typed accessor Field<T> with a column name.
  5. Using the strongly typed accessor Field<T> with a column name and a data row version.

using System;
using System.Data.SqlClient;
using System.Data;

namespace RetrieveValuesfromDataRowArray
{
class Program
{
static void Main(string[] args)
{
// Create a connection string
string objConnectString = "Data Source=(local);Initial Catalog=AdventureWorks;User ID=sa;Password=sa1234";

string objQuery = "SELECT ProductID,Name,ProductNumber,StandardCost FROM Production.Product WHERE ProductID BETWEEN 514 AND 522";

// Create a data adapter
SqlDataAdapter objDataAdapter= new SqlDataAdapter(objQuery, objConnectString);

// Fill a DataTable using DataAdapter
DataTable objDt = new DataTable();
objDataAdapter.Fill(objDt);

// Create and fill the DataRow array
DataRow[] objDataRowArray = new DataRow[objDt.Rows.Count];
objDt.Rows.CopyTo(objDataRowArray, 0);

// Using different techniques access DataRow array Product Name value in row 2
Console.WriteLine("Product Name = {0}", objDataRowArray[1][1]);
Console.WriteLine("Product Name = {0}", objDataRowArray[1]["Name"]);
Console.WriteLine("Product Name = {0}", objDataRowArray[1]["Name", DataRowVersion.Default]);
Console.WriteLine("Product Name = {0}", objDataRowArray[1].Field<string>(1));
Console.WriteLine("Product Name = {0}", objDataRowArray[1].Field<string>("Name"));
Console.WriteLine("Product Name = {0}", objDataRowArray[1].Field<string>("Name", DataRowVersion.Default));

Console.WriteLine("\nPress any key to continue.");
Console.ReadLine();

}
}
}



Output :


DataRowArray.png


Ebook Download
View all
Learn
View all