samoncode
samoncode

Reputation: 476

Select multiple ListItems in an <asp:ListBox> from codebehind c#

I've got a ListBox(with selectionMode=multiple) and store the selected values in a cookie. When the user comes back I want to provide him with all the options selected again.

What I do so far: I get all the selected values and store the indices ","-separated in a string in the cookie.

When the user comes back I split the string and loop through all ListItems to select each one again!

but with:

foreach (string str in selectedStr)
{
    listbox1.SelectedIndex = Int32.Parse(str);
}

I only get one (random?) selected value.

Can anyone help me to get all the selected values selected again? maybe even a better solution?

Upvotes: 0

Views: 3767

Answers (2)

Amol Kolekar
Amol Kolekar

Reputation: 2325

Just try using FindByValue property of Listview as follow...

foreach (string str in selectedStr)
{
    if(listbox1.Items.FindByValue(str) != null) 
    { 
          listbox1.Items.FindByValue(str).Selected = true; 
    } 
}

Upvotes: 3

Habib
Habib

Reputation: 223207

You can iterate through your splitted string array, and access the ListBox.Items[] based on the index and set the Selected property to true.

foreach (string str in selectedStr)
{
    listbox1.Items[Int32.Parse(str)].Selected = true;
}

Make sure that str is indeed an integer and its in range with Items.Length

Upvotes: 2

Related Questions