Posts Tagged ‘Unable to cast object’

Have your ever tried getting listbox items from Session and assigning it to another listbox?

If you do so,make sure that while getting back from Session,you cast it to System.Web.UI.WebControls.ListItemCollection.If you try casting to a list or arraylist it will throw exception similar as below:

Unable to cast object of type ‘System.Web.UI.WebControls.ListItemCollection’ to type ‘System.Collections.Generic.List`1[System.Web.UI.WebControls.ListViewDataItem]’

Session["ListViewStore"] = ListBox1.Items;

if (Session["ListViewStore"] != null)
{
System.Web.UI.WebControls.ListItemCollection list = (System.Web.UI.WebControls.ListItemCollection)Session["ListViewStore"];
foreach (ListItem item in list)
{
ListBox2.Items.Add(item);
}
}

Advertisements