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:

ListBox3.aspx
<%@ Page Language="C#" Inherits="BasePage" Src="ListBox3.aspx.cs" %>
<html>
  <body>
    <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" />
    </form>
  </body>
</html>

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.

ListBox3.aspx.cs
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=127.0.0.1\\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;
    list.DataBind();
  }
  
  public void HandleSelect(object sender, EventArgs e) {
    label.Text = "employee number = ";
    if (list.SelectedItem != null) label.Text += list.SelectedItem.Value;
  }
}

Try it

   http://dotnet.jku.at/book/samples/6/ListBox3.aspx