Search code examples
c#asp.netdictionarycastingrepeater

casting error on binding dictionary to repeater asp.net


I am trying to populate <li> items with a repeater, binding it to a Dictionary object. I have a dictionary called cart, with standard Key, Value properties.

I get a runtime error:

`System.InvalidCastException: Specified cast is not valid.`

I used this code:

<ItemTemplate>
<li id="<%# ((KeyValuePair<string,string>)Container.DataItem).Key %>_i" >
<%# ((KeyValuePair<string,string>)Container.DataItem).Key %> <%# ((KeyValuePair<string,string>)Container.DataItem).Value %>
</li></ItemTemplate>

What is wrong here?


Solution

  • Your ItemTemplate works for me when binding to a Dictionary<string, string>. Therefore, I'd suggest to check whether the Repeater is really bound to a Dictionary<string, string>.

    If not, the exception makes sense and can be solved by fixing the data binding code (or changing the type that is used in the ItemTemplate so that it matches the data that is bound to the Repeater.