Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can you store a listbox or arraylist in a session variable?

Status
Not open for further replies.

j9

Programmer
Jun 6, 2001
90
0
0
US
Hi,

I'd like to store the contents of a listbox in a session variable. No error is produced from the assignment statement, but I cannot retrieve the items from the session variable afterwards. Thanks.

//The following code is in page load...
if(Session["lstGrpMembers"] == null)
{
//set the session variable equal to the webform's listbox
//this does not produce an error
Session["lstGrpMembers"] = this.lstGrpMembers;
}
else
{
//this code throws an error because the session variable does not have an 'Items' property.
foreach (ListItem itmGrpMember in Session ["lstGrpMembers"].Items)
{
lstGrpMembers.Items.Add(itmGrpMember);
}
}
 
Not sure exactly what you're trying to do but here's a simple example. I've got two ListBoxes and a button on the aspx page. One is populated with ListItems, the other isn't. The Page_Load reads the items in ListBox1 and loads them into an ArrayList which is then stuffed into a session variable.
Code:
private void Page_Load(object sender, System.EventArgs e)
{						
	if(!Page.IsPostBack)
	{
	ArrayList myList = new ArrayList();
	foreach(ListItem li in ListBox1.Items)
	{
		myList.Add(li);
	}
	Session["myArray"] = myList;

	}		
}
In the Button1_Click event I create a new ArrayList and populate it with the Session variable. Then iterate through it and populate ListBox2 with the items. This should give you an idea of what you can do.
Code:
private void Button1_Click(object sender, System.EventArgs e)
{
	ArrayList mySessionArray = (ArrayList)Session["myArray"];
	foreach(ListItem li in mySessionArray)
	{
		ListBox2.Items.Add(li);
	}
}
 
can you just store the items in the ddl in a session variable that is a datatable instead? then assign it in the next page...

lstGrpMembers.Datasource = cType(Session("membersDT"), DataTable)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top