【问题标题】:ASP .NET Nested ListView is not recognizedASP .NET 嵌套 ListView 无法识别
【发布时间】:2012-10-29 20:54:32
【问题描述】:

我有以下使用嵌套 ListView 的示例代码:

<asp:ListView ID="list" runat="server" ItemPlaceholderID="placeHolder"
        OnItemDataBound="listItemDataBound">
    <ItemTemplate>
        <p><%#Eval("name") %></p>
        <asp:ListView ID="sublist" runat="server" ItemPlaceholderID="subPlaceHolder">
            <ItemTemplate><%#Eval("subName") %></ItemTemplate>
            <LayoutTemplate>
                <asp:PlaceHolder ID="subPlaceHolder" runat="server"></asp:PlaceHolder>
            </LayoutTemplate>
        </asp:ListView>
    </ItemTemplate>
    <LayoutTemplate>
        <asp:PlaceHolder ID="placeHolder" runat="server"></asp:PlaceHolder>
    </LayoutTemplate>
</asp:ListView>

但嵌套的 ListView(子列表)在我的脚本代码中未被识别为变量,因此我无法访问它并提供一些数据绑定。当我在主 ListView(例如 DataSource)中添加一些其他对象时,它也无法识别。 如何访问嵌套的 ListView?

感谢您的任何建议。

【问题讨论】:

  • 你的“脚本代码”是什么?你是说 JavaScript 吗?
  • 不,我的意思是 C# 服务器端代码,它处理主列表的 OnItemDataBound。嵌套的 ListView(子列表)在当前上下文中被报告为未知。
  • 能否显示您尝试运行的 OnItemDataBound 代码?

标签: c# asp.net .net


【解决方案1】:

ItemTemplate 中的控件将被创建多次,为数据源中的每个项目创建一次,因此编译器无法生成单个字段来表示它们。您需要改用FindControl

protected void listItemDataBound(object sender, ListViewItemEventArgs e)
{
   var sublist = (ListView)e.Item.FindControl("sublist");
   ...
}

【讨论】:

  • 谢谢,这正是我正在寻找的。​​span>
【解决方案2】:

在您的 OnItemDataBound 事件代码中,您必须这样做:

 if (e.Item.ItemType == ListViewItemType.DataItem)
 {
    ListView sublist = (ListView)e.Item.FindControl("sublist");
 }

为了找到你嵌套的 ListView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    相关资源
    最近更新 更多