ListView in ASP.NET and DataKeyNames



我有一个ListView,它与一个"a"列表绑定,看起来像这样:

Class A
    Property Id as Integer
    Property TestStringA as String
    Property B as B
End Class
Class B
    Property Id as Integer
    Property TestStringB as String
End Class

在ListView中,我可以引用"链接属性"值(正确的术语是什么?):

<asp:ListView runat="server" ID="lwTest" ItemType="A">
    <LayoutTemplate>
        <tr runat="server" id="itemPlaceHolder"></tr>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
             <td><%# Item.TestStringA %></td>
             <td><%# Item.B.TestStringB %></td> (this is what I mean)
        </tr>
    </ItemTemplate>
</asp:ListView>

当使用Eval方法时(如果不能使用"ItemType"),这也是有效的:

<%# Eval(B.TestStringB) %>

我想循环ListView的项并使用容器中的值,而不将它们保存在隐藏字段中(这不是"DataKeyNames"的目的吗?)。问题是,我不能通过DataKeyNames中的链接属性/属性(在示例B.Id中)来引用另一个对象的属性。当我这样做时,我会收到一个错误,告诉我没有名为"B.Id"的属性):

<asp:ListView runat="server" ID="lwTest" ItemType="A" DataKeyNames"Id, B.Id">
    <LayoutTemplate>
        <tr runat="server" id="itemPlaceHolder"></tr>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
             <td><%# Item.TestStringA %></td>
             <td><%# Item.B.TestStringB %></td> (this is what I mean)
        </tr>
    </ItemTemplate>
</asp:ListView>

有人知道这是否可能吗?我知道我可以添加只读属性,将值直接返回到绑定对象(但如果可能的话,我希望避免这种情况):

Class A
    Property Id as Integer
    Property TestStringA as String
    Property B as B
    ReadOnly Property BId as Integer
        Get
            Return B.Id
        End Get
    End Property
End Class
Class B
    Property Id as Integer
    Property TestStringB as String
End Class

提前谢谢!

首先,您只能使用类的直接属性作为DataKeyNames。有了Eval指令,你可以更深入(但我相信只有一个级别)。

您可以做的是通过后面的代码更改列表视图中显示的内容。

要执行此操作,请添加ItemDataBound事件。正在创建的项的数据可以在e.item.DataItem结尾将是类型A(使用前请强制转换)。

你应该能够直接通过e.Item访问你的控件(不知道在这个单元格上要记住哪些属性),一旦你找到了正确的单元格,你就可以为它设置任何你想要的文本,因为你有A本身的绑定实例,所以你可以无限制地调用任何你需要的属性或子属性。

这个函数会为ListView中的每个条目调用,所以它们应该只为您提供当前条目的数据。

希望这能帮助你解决问题。

最新更新