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>

- How to use SqlConnection
- How to create a DataTable
- How to add a calculated column to a DataTable
- How to set maximum size of a column in a DataTable
- How to check if a column exists in a DataTable
- How to get index of a column by name in a DataTable
- How to get a DataTable columns data type
- How to get maximum size of a column in a DataTable
- How to add a new row into DataTable
- How to change DataTable columns order