JayOnDotNet
JayOnDotNet

Reputation: 398

Add listbox to session

Hi I have a listbox in my asp page.How to add listbox items to session to persists between page navigations

Can any one help

Upvotes: 0

Views: 3648

Answers (2)

Ahmed
Ahmed

Reputation: 655

You can do something like this.

    ListBox mylist = new ListBox();
    mylist.Items.Add(new ListItem("Tahir", "Tahir"));
    Session["ITEM"] = mylist;
    foreach (ListItem Item in ((ListBox)(Session["ITEM"])).Items)
    {          
        mylist.Items.Add(new ListItem(Item.Text, Item.Value));
    }

however you might want to put some check that whether session actually contains a listbox or not because the first time you load your page there will be no listbox in session and you have to store it as you load the page and then use it as you like.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460228

By default you can store any type of object in Session because it's stored in memory. So you could use it to store the ListItemCollection of the ListBox.

Session["MyListBoxItems"] = ListBox1.Items.Cast<ListItem>().ToArray();

and afterwards you can use AddRange to restore them:

ListBox1.Items.AddRange((ListItem[])Session[ "MyListBoxItems" ]);

Edit: If you are using an older framework version use CopyTo:

ListItem[] myListItemArray = new ListItem[ ListBox1.Items.Count ];
ListBox1.Items.CopyTo(myListItemArray, 0);
Session[ "MyListBoxItems" ] = myListItemArray;

Upvotes: 3

Related Questions