'How to set multiple items as selected in ListBox?

I have one ListBox with selection mode of multiple. In code behind, I want to set some values as selected. These values are present in a ListItems[] named 'Names'.

HTML code:

<asp:ListBox ID="lbto" class="chosen" runat="server" Width="450px" 
 Height="20px" SelectionMode="Multiple">
    <asp:ListItem>Mandy</asp:ListItem>
    <asp:ListItem>Amit</asp:ListItem>
    <asp:ListItem>sundar</asp:ListItem>
    <asp:ListItem>ragu</asp:ListItem>
    <asp:ListItem>raju</asp:ListItem>
</asp:ListBox>

ListItem[] Names contains 'ragu' and 'raju'. Now, when the page loads, the ListBox should contain 'ragu' and 'raju' as selected values.



Solution 1:[1]

You can use FindByValue method

foreach (string item in stringList)
    lbxList.Items.FindByValue(item).Selected = true;

Solution 2:[2]

int[] IndexList = new int[] { 1, 3, 5, 7, 9 };
for (int i = 0; i < IndexList.Length; i++)
{
    if (listBox1.Items.Count > IndexList[i])
    {
        listBoxFX.SetSelected(IndexList[i], true);
    }
}

Solution 3:[3]

Using One line of linq

lbto.Items.Cast<String>().ForEach(i => i.Selected = names.Contains(i.Text));

OR

lbto.Items.OfType<string>().ForEach(i => i.Selected = names.Contains(i.Text));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carsten
Solution 2 Ideoken
Solution 3