C# 将字典绑定到repeater asp.net时强制转换错误
我试图用一个转发器填充C# 将字典绑定到repeater asp.net时强制转换错误,c#,asp.net,dictionary,casting,repeater,C#,Asp.net,Dictionary,Casting,Repeater,我试图用一个转发器填充项,将其绑定到一个Dictionary对象。我有一个名为cart的字典,具有标准的键、值属性 我收到一个运行时错误: `System.InvalidCastException: Specified cast is not valid.` 我使用了以下代码: <ItemTemplate> <li id="<%# ((KeyValuePair<string,string>)Container.DataItem).Key %>_i" &
项,将其绑定到一个Dictionary对象。我有一个名为cart的字典,具有标准的键、值属性
我收到一个运行时错误:
`System.InvalidCastException: Specified cast is not valid.`
我使用了以下代码:
<ItemTemplate>
<li id="<%# ((KeyValuePair<string,string>)Container.DataItem).Key %>_i" >
<%# ((KeyValuePair<string,string>)Container.DataItem).Key %> <%# ((KeyValuePair<string,string>)Container.DataItem).Value %>
</li></ItemTemplate>
这里出了什么问题?当绑定到
词典时,您的ItemTemplate对我很有效。因此,我建议检查中继器是否真的绑定到了字典
如果不是,则异常是有意义的,可以通过修复数据绑定代码(或更改ItemTemplate中使用的类型,使其与绑定到中继器的数据匹配)来解决异常。如果您的字典不是字典,您可以执行以下操作
((System.Collections.Generic.KeyValuePair<string,byte[]>)(Container.DataItem)).Key
((System.Collections.Generic.KeyValuePair)(Container.DataItem)).Key
或
((System.Collections.Generic.KeyValuePair)(Container.DataItem)).Key.ProductCode
当绑定到字典时,您的ItemTemplate对我有效。您确定错误与ItemTemplate中的绑定有关吗?您是否有OnItemDataBound事件处理程序?字典的类型是否为字典
?是否可以添加错误的堆栈跟踪?谢谢您检查我的代码,您是正确的错误与ItemTemplate无关。我错误地将数据源设置为字典的值,而不是字典本身。非常感谢!它现在可以工作了!@user26333600:很高兴听到它可以工作。我添加了一个答案。
((System.Collections.Generic.KeyValuePair<clsProduct,int>)(Container.DataItem)).Key.ProductCode