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.

ListBox2.aspx
<%@ Import Namespace="System.Collections" %>
<%@ Page Language="C#" %>
<html>
  <head>
    <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
        list.DataBind();
      }

      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;
      }
    </script>
  </head>
  <body>
    <form Runat="server">
      <asp:ListBox ID="list" Rows="3" Runat="server" AutoPostBack="true"
        OnSelectedIndexChanged="Show" />
      <br><br>
      <asp:Button OnClick="Fill" Text="Fill" Runat="server" />
      <br><br>
      <asp:Label ID="lab" Runat="server" />
    </form>
  </body>
</html>

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.

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