Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Get the column ordinal for the Phone attribute and use it to output the column

using System; using System.Data; using System.Data.SqlClient;     class Program     {         static void Main(string[] args)         {             string sqlConnectString = "Data Source=(local);" +                 "Integrated security=SSPI;Initial Catalog=AdventureWorks;";             string sqlSelect = @"SELECT ContactID, NameStyle, Title,                 FirstName, MiddleName, LastName, Suffix, EmailAddress,                 EmailPromotion, Phone, PasswordHash, PasswordSalt                 FROM Person.Contact";             SqlConnection connection = new SqlConnection(sqlConnectString);             SqlCommand command = new SqlCommand(sqlSelect, connection);             connection.Open( );             SqlDataReader dr = command.ExecuteReader( );             dr.Read( );             int coPhone = dr.GetOrdinal("Phone");             Console.WriteLine("Phone = {0}", dr[coPhone]);         }     }