views:

63

answers:

1

I have a portion of code where I nest repeaters by hardcoding them in HTML:

    <asp:Repeater ID="rpt_1" runat="server">
        <ItemTemplate>
            <div><%# Eval("ID") %></div>
             <asp:Repeater ID="rpt_2" runat="server">
                 <ItemTemplate>
                      <div><%# Eval("ID") %></div>
                      <asp:Repeater ID="rpt_3" runat="server">
                          <ItemTemplate>
                              <div><%# Eval("ID") %></div>
                          </ItemTemplate>
                      </asp:Repeater>
                 </ItemTemplate>
             </asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>

Each repeater's ItemTemplate has exactly the same HTML and layout stuff. Is there a way to programatically nest them n number of repeaters based on the layout of one? Here's kind of pseduo code of what I want to do:

     <asp:Repeater ID="rpt_1" runat="server">
        <ItemTemplate>
            <div><%# Eval("ID") %></div>
             <asp:Repeater ID="rpt_2" runat="server"/>                
        </ItemTemplate>
    </asp:Repeater>

   rpt_1.ItemDataBound += new RepeaterItemEventHandler(rpt_ItemDataBound);
   rpt_1.DataSource = q;
   rpt_1.DataBind();

protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (sender is Repeater)
    {
        string strID = ((Repeater)sender).ID.ToString();
        strID = strID.Substring(strID.Length - 1, 1).ToString();
        Repeater rpt = (Repeater)e.Item.FindControl("rpt_" + strID);

        if (strID != "4")
        {//Stop the nested creation

        //Does this work?
        //How do I accomplish this?
        rpt.ItemTemplate = (Repeater)e.Item.FindControl("rpt_" + (Convert.ToInt32(strID)-1).ToString()).ItemTemplate;

        rpt_1.ItemDataBound += new RepeaterItemEventHandler(rpt_ItemDataBound);
        rpt.DataSource = q;
        rpt.DataBind();
        }
    }
}

Can I assign the ItemTemplate of one repeater to another in code?

A: 

You can create your template in an ascx file, and then load it like this:

rpt_1.LoadTemplate(template_file.ascx);

Do this before you call DataBind();

Ray