use the GetOrdinal() from DataReader to get the numeric positions of a column : SqlDataReader « Database « C# / C Sharp

use the GetOrdinal() from DataReader to get the numeric positions of a column


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

class UsingColumnOrdinals {
    public static void Main() {
        SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");

        SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

        mySqlCommand.CommandText =
          "SELECT TOP 5 ProductID, ProductName, UnitPrice, " +
          "UnitsInStock, Discontinued " +
          "FROM Products " +
          "ORDER BY ProductID";


        SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();

        int productIDColPos = productsSqlDataReader.GetOrdinal("ProductID");
        int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName");
        int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice");
        int unitsInStockColPos = productsSqlDataReader.GetOrdinal("UnitsInStock");
        int discontinuedColPos = productsSqlDataReader.GetOrdinal("Discontinued");

        while (productsSqlDataReader.Read()) {
            Console.WriteLine("ProductID = " + productsSqlDataReader[productIDColPos]);
            Console.WriteLine("ProductName = " + productsSqlDataReader[productNameColPos]);
            Console.WriteLine("UnitPrice = " + productsSqlDataReader[unitPriceColPos]);
            Console.WriteLine("UnitsInStock = " + productsSqlDataReader[unitsInStockColPos]);
            Console.WriteLine("Discontinued = " + productsSqlDataReader[discontinuedColPos]);



Related examples in the same category

1.Execute multiple SELECT statements using a SqlCommand object and read the results using a SqlDataReader object
2.Get column index from SqlDataReader to read column values as C# types using the Get* methods column values as Sql* types using the GetSql* methods
5.Read data from SqlDataReader
6.Reference data in SqlDataReader by column name
7.Use A Data Reader
8.Use While loop to read query result data from SqlDataReader
9.Deal with Multiple Results
10.SqlDataReader Ordinal Indexer