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

Posted: January 13, 2011 in Controls
Tags: , , ,

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s