ASP.Net ListBox control allows two types of selection mode: single and multiple. Working in single selection mode is similar to working with DropDown list control. Use ListBox.SelectedValue to get the value that was selected by a user. In order to set a selection SelectedIndex property can be used or Selected property of a particular item should be set to true.
Example:
string selectedValue = MyListBox.SelectedValue; //get selected value
MyListBox.SelectedIndex = 0; //set the first item to be selected
MyListBox.Items.FindByValue("val2").Selected = true; //select the item with value="val2"
However when using ListBox with SelectionMode="Multiple" ListBox.SelectedValue will return only the first selected item, not all of them. The code below shows how to create a simple extension method for a ListBox that will allow to get and set multiple selected items.
public static class ListBoxExtensions
{
//return ArrayList of selected values
public static ArrayList SelectedValues(this ListBox lbox)
{
ArrayList selectedValues = new ArrayList();
int[] selectedIndeces = lbox.GetSelectedIndices();
foreach (int i in selectedIndeces)
selectedValues.Add(lbox.Items[i].Value);
return selectedValues;
}
/// <summary>
/// Select multiple items in a ListBox
/// </summary>
/// <param name="values">Values of the items that need to appear selected</param>
public static void SelectedValues(this ListBox lbox, string[] values)
{
foreach (string value in values)
{
ListItem item = lbox.Items.FindByValue(value);
if (item != null)
item.Selected = true;
}
}
}
Example:
<asp:ListBox ID="MyListBox" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="ItemText1" Value="val1"></asp:ListItem>
<asp:ListItem Text="ItemText2" Value="val2"></asp:ListItem>
<asp:ListItem Text="ItemText3" Value="val3"></asp:ListItem>
<asp:ListItem Text="ItemText4" Value="val4"></asp:ListItem>
<asp:ListItem Text="ItemText5" Value="val5"></asp:ListItem>
</asp:ListBox>
To set items to be selected use
MyListBox.SelectedValues(new string[] {"val1", "val3"});
To get selected values call
ArrayList selectedValues = MyListBox.SelectedValues();
