Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
ragu Avatar asked Apr 11 '13 08:04

ragu


1 Answers

What about setting the Selected-property of the ListItem?

var names = new List<string>(new string[] { "ragu", "raju" });

foreach (var item in lbto.Items)
{
    if (names.Contains(item.Text))
        item.Selected = true;
}
like image 109
Carsten Avatar answered Oct 09 '22 06:10

Carsten