Keeping ListBox selections in session on a postback

426 Views Asked by At

As you can see below, i know how to do it for one selection, but this only works for the most recent single selection, i want to do it for several selections made.

Session["SelectedListItem"] = this.LstRecipients.SelectedValue;

if (Session["SelectedListItem"] != null)
{
    this.LstRecipients.SelectedValue = (string)Session["SelectedListItem"];
}

How can i store multiple selections made in a listbox in session and then reselect these selections on postback?

1

There are 1 best solutions below

3
Tim Schmelter On BEST ANSWER

You can store anything in the session, so you can store it as string[] or List<string>:

string[] selectedValues = this.LstRecipients.Items.Cast<ListItem>()
    .Where(i => i.Selected)
    .Select(i => i.Value)
    .ToArray();
Session["SelectedItemValues"] = selectedValues;

/* on next postback you can retrieve the values in this way: */
var selectedValues = Session["SelectedItemValues"] as string[];
if (selectedValues != null)
{
    foreach(ListItem item in this.LstRecipients.Items)
       item.Selected = selectedValues.Contains(item.Value);
}