The ListBox control is used to create a list control that allows single or multiple item selection. Use the Rows property to specify the height of the control. By default, the ListBox only allows a single selection to be made at a time. To enable the selection of multiple items, set the SelectionMode property to "Multiple".
To specify the items that you want to appear in the ListBox control, place a ListItem element for each entry between the opening and closing tags of the ListBox control.
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Value="">Please select an item</asp:ListItem>
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
</asp:ListBox>
The ListBox control also supports data binding. To bind the control to a data source, first create a data source, such as one of the DataSourceControl objects, that contains the items to display in the control. Next, use the DataBind method to bind the data source to the ListBox control. Use the DataTextField and DataValueField properties to specify which field in the data source to bind to the Text and Value properties, respectively, of each list item in the control. The ListBox control will now display the information from the data source.
By default, when the control is databound, any ListItems currently in the items collection will be removed. Sometimes we might wish to add a single "blank" item with the text "Please select an item". To insure that this item is not removed during the databinding process, we can set the AppendDataboundItems propert to "true".
<asp:ListBox ID="ListBox2" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="">Please select an item</asp:ListItem>
</asp:ListBox>
If the SelectionMode property is set to Multiple, you can determine the selected items in the ListBox control by iterating through the Items collection and testing the Selected property of each item in the collection. If the SelectionMode property is set to Single, you can use the SelectedIndex property to determine the index of the selected item. The index can then be used to retrieve the item from the Items collection.
VB
'test for multiple selections
Dim selectionList As New System.Collections.Generic.List(Of String)
For Each itm As ListItem In ListBox1.Items
If itm.Selected = True Then
selectionList.Add(itm.Value)
End If
Next
'get single selection value
Dim selectionValue As String
selectionValue = Me.ListBox1.SelectedValue
'or
Dim selectedItem As ListItem
selectedItem = Me.ListBox1.SelectedItem
C#
//test for multiple selections
System.Collections.Generic.List<string> selectionList = new System.Collections.Generic.List<string>();
foreach (ListItem itm in ListBox1.Items)
{
if (itm.Selected == true)
{
selectionList.Add(itm.Value);
}
}
//get single selection value
string selectionValue;
selectionValue = this.ListBox1.SelectedValue;
//or
ListItem selectedItem;
selectedItem = this.ListBox1.SelectedItem;