Using a ADO.NET SqlDataReader Object in C#

Add a Button control (btnGetCustomers) and a ListBox control (lbCustomers) to your form/page.

using System.Data;
using System.Data.SqlClient;
 
private void btnGetCustomers_Click(object sender,
     System.EventArgs e)
{
    // Connect to the database
    SqlConnection cnn = new SqlConnection();
    cnn.ConnectionString = "Data Source=(local);" +
    "Initial Catalog=Northwind;" +
    "Integrated Security=SSPI";
    // Create a new ad hoc query
    // to retrieve customer names
    SqlCommand cmd = cnn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText =
        "SELECT CompanyName FROM Customers "
    + " ORDER BY CompanyName";
    // Dump the data to the user interface
    cnn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        lbCustomers.Items.Add(dr.GetString(0));
    }
    // Clean up
    dr.Close();
    cnn.Close();
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.