【问题标题】:casting error on binding dictionary to repeater asp.net将字典绑定到中继器 asp.net 时出现转换错误
【发布时间】:2014-03-30 10:27:38
【问题描述】:

我正在尝试使用转发器填充 <li> 项目,并将其绑定到 Dictionary 对象。我有一本名为 cart 的字典,具有标准的 Key、Value 属性。

我收到运行时错误:

`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>

这里有什么问题?

【问题讨论】:

  • 当绑定到 Dictionary&lt;string, string&gt; 时,您的 ItemTemplate 对我有效。您确定该错误与 ItemTemplate 中的绑定有关吗?您有 OnItemDataBound 事件处理程序吗?字典的类型是Dictionary&lt;string, string&gt;吗?可以添加错误的 StackTrace 吗?
  • Markus 感谢您检查我的代码,您是正确的,错误与 ItemTemplate 无关。我错误地将 DataSource 设置为字典的值而不是字典本身。非常感谢!现在可以了!
  • @user26333600:很高兴听到它有效。我已经添加了答案。

标签: c# asp.net dictionary casting repeater


【解决方案1】:

绑定到Dictionary&lt;string, string&gt; 时,您的 ItemTemplate 对我有效。因此,我建议检查中继器是否真的绑定到Dictionary&lt;string, string&gt;。

如果不是,该异常是有意义的,可以通过修复数据绑定代码(或更改 ItemTemplate 中使用的类型,使其与绑定到中继器的数据匹配)来解决。

【讨论】:

    【解决方案2】:

    如果您的字典不是Dictionary&lt;string, string&gt;,您可以执行类似的操作

    ((System.Collections.Generic.KeyValuePair<string,byte[]>)(Container.DataItem)).Key
    

    或者

    ((System.Collections.Generic.KeyValuePair<clsProduct,int>)(Container.DataItem)).Key.ProductCode
    

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多