1

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.

3
  • what is your 'script code'? Do you mean JavaScript? Commented Oct 29, 2012 at 12:32
  • No, I mean C# server-side code, which handle OnItemDataBound of the main list. Nested ListView (sublist) is reported as not known in the current context. Commented Oct 29, 2012 at 12:39
  • Could you show the OnItemDataBound code you're trying to run? Commented Oct 29, 2012 at 12:42

2 Answers 2

2

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");
   ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's exactly I was searching for.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.