Tag Archives: ADO.NET

ADO.NET Read single row

Just use CommandBehavior.SingleRow as an argument in ExecuteReader()

string queryString = "SELECT TOP 100 ProductID, ListPrice, Name from Production.Product ORDER BY ListPrice DESC;";
using (SqlConnection conn = new SqlConnection(MyConnectionString))
{
    using (SqlCommand command = new SqlCommand(queryString, conn))
    {
        try
        {
            conn.Open();
            SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
            while (reader.Read())
            {
                Console.WriteLine("\t{0}\t{1}\t{2}", reader[0], reader[1], reader[2]);
            }
            reader.Close();
        }
        catch (Exception ex)
        {
            // handle error
        }
    }
}