c# - How to read data with SqlDataReader

SqlDataReader Read() Method
SqlDataReaderExample.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) { 
        if(!Page.IsPostBack)
        {
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            SqlCommand myCommand = new SqlCommand();
            myCommand.CommandType = CommandType.Text;
            myCommand.CommandText = "SELECT CategoryID, CategoryName FROM Categories";
            myCommand.Connection = myConnection;
            SqlDataReader myReader;

            try
            {
                myConnection.Open();
                myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    ListItem li = new ListItem();
                    li.Value = myReader["CategoryID"].ToString();
                    li.Text = myReader["CategoryName"].ToString();
                    ListBox1.Items.Add(li);
                }
                myReader.Close();
            }
            catch (Exception err)
            {
                Response.Write("Error: ");
                Response.Write(err.ToString());
            }
            finally
            {
                myConnection.Close();
            }
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net SqlDataReader example: how to use Read() method to populate ListBox</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">SqlDataReader Example</h2>
        <asp:ListBox ID="ListBox1" runat="server" BackColor="DeepSkyBlue" ForeColor="AliceBlue" >
        </asp:ListBox>
    </div>
    </form>
</body>
</html>
More c# examples