Ivo Pavlik
Ivo Pavlik

Reputation: 297

ASP .NET Nested ListView is not recognized

I have following sample code, which uses nested 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>

But nested ListView (sublist) is not recognized as a variable in my script code, so I can't access it and provide some databinding. When I add some other object inside main ListView (e.g. DataSource), it is also not recognized. How can I access nested ListView?

Thanks for any suggestion.

Upvotes: 1

Views: 1278

Answers (2)

markpsmith
markpsmith

Reputation: 4918

Within your OnItemDataBound event code, you'll have to do this:

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

In order to find your nested ListView

Upvotes: 0

Richard Deeming
Richard Deeming

Reputation: 31208

Controls in the ItemTemplate will be created multiple times, once for each item in your data source, so the compiler cannot generate a single field to represent them. You'll need to use FindControl instead:

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

Upvotes: 2

Related Questions