The ListBox Web Control

The ListBox Web Control

The ListBox control represents a vertical sequence of items displayed in a scroll­able window. As shown in the following code, ListBox allows single or multiple item selection and exposes its contents by using the familiar Items collection:

<asp:listbox runat="server" id="theListBox" 
    rows="5" selectionmode="Multiple" />

You can determine the height of the control by using the Rows property. As you might have guessed, the height is measured in numbers of rows rather than in pixels or percentages.

When it comes to data binding, the ListBox control behaves like the other controls discussed earlier in the chapter—that is, it supports properties such as DataSource, DataMember, DataTextField, DataValueField, and DataText­FormatString, and it can be bound to a data source and show its contents, as follows:

lstEmp.DataSource = ds.Tables["EmpTable"];
lstEmp.DataTextField = "lastname";
lstEmp.DataValueField = "employeeid";

The next code snippet illustrates how to write a comma-separated string with the values of the selected items. (This code is nearly identical to the code you would write to accomplish the same operation for a CheckBoxList control.)

public void ShowSelectedItems(Object sender, EventArgs e)
    StringBuilder sb = new StringBuilder("");
    for (int i=0; i < lstEmp.Items.Count; i++)
        if (lstEmp.Items[i].Selected)
            sb.Append(", ");
    lblResults.Text = sb.ToString(); 

Figure 1-3 shows the results of the code. The full source for the ListBox.aspx application is available on the companion CD.

Figure 1-3
This sample application illustrates the use of a data bound, multi-selection list box.

The programming interface of the list box also contains a SelectedItem property, which at first appears to make little sense because you are working with a multi-selection control. In this case, however, the SelectedItem property returns the selected item with the lowest index.