Home   Cover Cover Cover Cover

ListBox With Dynamically Specified Entries

From Section 6.4.9 of the book

This example shows how to build a ListBox from dynamically specified list items. The items denote countries. If an item is selected the international car code of this country is displayed.

<%@ Import Namespace="System.Collections" %>
<%@ Page Language="C#" %>
    <script Language="C#" Runat="server">
      void Fill(object sender, EventArgs e) {
        SortedList data = new SortedList();
        data["United States"] = "USA";
        data["Great Britain"] = "GB";
        data["Germany"] = "D";
        data["France"] = "F";
        data["Italy"] = "I";
        list.DataSource = data;
        list.DataTextField = "Key";    // take the text from the Key property of the items
        list.DataValueField = "Value"; // take the value from the Value property of the items

      void Show(object sender, EventArgs e) {
        lab.Text = "The selected country has the international car code ";
        if (list.SelectedItem != null) lab.Text += list.SelectedItem.Value;
    <form Runat="server">
      <asp:ListBox ID="list" Rows="3" Runat="server" AutoPostBack="true"
        OnSelectedIndexChanged="Show" />
      <asp:Button OnClick="Fill" Text="Fill" Runat="server" />
      <asp:Label ID="lab" Runat="server" />

Try it

After clicking on the link below a web page with an empty ListBox is opened. By clicking on the button the ListBox is filled with items. Then select an item.