Home   Cover Cover Cover Cover

ListBox With Entries from a Database

From Sectio 6.4.9 of the book

In this example a ListBox is filled with items from a database. The following code shows the aspx page that defines the ListBox:

<%@ Page Language="C#" Inherits="BasePage" Src="ListBox3.aspx.cs" %>
    <form OnInit="PageInit" Runat="server">
      <asp:ListBox ID="list" Runat="server" AutoPostBack="true"
        DataTextField="LastName" DataValueField="EmployeeID"
        OnSelectedIndexChanged="HandleSelect" /><br>
      <asp:Label ID="label" Runat="server" />

The script code for this page is stored in a code-behind file. It opens a connection to the Northwind database, which comes with .NET as a sample dabase. All employees are retrieved from this database and added to the ListBox. If a list item is selected the corresponding employee number is displayed.

using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

public class BasePage : Page {
  protected ListBox list;
  protected Label label;
  public void PageInit(object sender, EventArgs e) {
    DataSet ds = new DataSet();
    SqlConnection con = new SqlConnection("data source=\\NETSDK; " +
      "initial catalog=Northwind; user id=sa; password=; Trusted_Connection=true");
    string cmdString = "SELECT * FROM Employees";
    SqlDataAdapter adapter = new SqlDataAdapter(cmdString, con);
    adapter.Fill(ds, "Employees");
    if (ds.HasErrors) ds.RejectChanges(); else ds.AcceptChanges();
    list.DataSource = ds.Tables["Employees"].DefaultView;
  public void HandleSelect(object sender, EventArgs e) {
    label.Text = "employee number = ";
    if (list.SelectedItem != null) label.Text += list.SelectedItem.Value;

Try it