Unable to cast object from viewstate to collection

989 views Asked by At

I'm storing a collection of List<KeyValuePair<string, bool>> in ViewState, the problem occurs when i'm trying to cast it back to List<KeyValuePair<string, bool>> Error states

Unable to cast object of type 'System.Collections.Generic.Dictionary2[System.String,System.Boolean]' to type 'System.Collections.Generic.List1[System.Collections.Generic.KeyValuePair`2[System.String,System.Boolean]]'.

So how can convert my key value list back from the ViewState ?

My code line is:

List<KeyValuePair<string, bool>> myObject = (List<KeyValuePair<string, bool>>)ViewState["listOutputWords"];
2

There are 2 answers

0
Rahul Singh On BEST ANSWER

Try this:-

KeyValuePair<string, bool> myObject = (KeyValuePair<string, bool>)ViewState["listOutputWords"];

As clearly mentioned by the compiler, your ViewState is holding a generic Dictionary of String,Bool but you are trying to cast it to List of Dictionary which is wrong.

0
Damir Arh On

Based on the exception, you're saving a Dictionary<string, bool> in ViewState. If you really need a List<KeyValuePair<string, bool>>, try:

List<KeyValuePair<string, bool>> myObject = ((Dictionary<string, bool>)ViewState["listOutputWords"]).ToList();

Or you could just deserialize it to a dictionary and use that:

Dictionary<string, bool> myObject = (Dictionary<string, bool>)ViewState["listOutputWords"];