Bob
Bob

Reputation: 382

ASP.Net Databinding inside a bound control

I'm having a littl fun with ASP.Net data binding today, basically I have two nested controls, and an collection of objects with their own internal collections which I wish to bind...

So, say I'm using two repeaters like this ->

    <asp:Repeater ID="Repeater1">
      <ItemTemplate>
        <asp:Label runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "HeaderText")%>'>
        </asp:Label>
        <asp:Repeater ID="Repeater2">
          <asp:Label runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "DetailText")%>'>
          </asp:Label>
        </asp:Repeater>
      </ItemTemplate>
    </asp:Repeater>

And my objects look like this:

    public class parent
    {
      public string HeaderText {get;set;}
      public List<child> children {get;set;}
    }
    public class child
    {
      public string DetailText {get;set;}
    }

How do I bind the inner repeater? I'm guessing that I need to set & bind the datasource of 'Repeater2' somewhere in the aspx to be the 'children' property of 'parent'?

Can someone point me in the right direction?

Thanks

Upvotes: 2

Views: 1186

Answers (2)

James Johnson
James Johnson

Reputation: 46047

You would bind the inner repeater in the ItemDatabound event of the outer repeater:

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Repeater innerRepeater = e.Item.FindControl("InnerRepeater1") as Repeater;
    if (innerRepeater != null)
    {
        innerRepeater.DataSource = GetSomeData();
        innerRepeater.DataBind();
    }
}

It might be easier to use a ListView or DataList if you need to use data from the outer databound control to bind the inner databound control, because you can specify datakeys.

<asp:ListView ID="ListView1" runat="server" DataKeyNames="SomeColumn" ...>

Code-behind:

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    ListView innerList = e.Item.FindControl("InnerList1") as ListView;
    if (innerList != null)
    {
        innerList.DataSource = GetSomeData((int)ListView1.DataKeys[ListView1.Items.IndexOf(e.Item)]["SomeColumn"]);
        innerList.DataBind();
    }
}

Upvotes: 1

Curtis
Curtis

Reputation: 103358

Bind the nested repeater in the main repeater ItemDataBound event.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx

Here you can find the control (FindControl) and bind to it.

It would be something like:

<asp:Repeater ID="Repeater1" OnItemDataBound="Repeater1_ItemDataBound">


void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
    Repeater Rep2 = e.Item.FindControl("Repeater2");
    Rep2.DataSource = //datasource here
    Rep2.DataBind();         
}    

Upvotes: 1

Related Questions