动态嵌套转发器ASP.net

时间:2010-08-29 16:41:41

标签: c# repeater nested-repeater

我有一部分代码可以通过在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>

每个转发器的ItemTemplate都具有完全相同的HTML和布局。有没有办法以编程方式将多个中继器嵌入其中?这是我想要做的pseduo代码:

     <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();
        }
    }
}

我可以在代码中将一个转发器的ItemTemplate分配给另一个转发器吗?

1 个答案:

答案 0 :(得分:0)

您可以在ascx文件中创建模板,然后像这样加载它:

rpt_1.LoadTemplate(template_file.ascx);

在调用DataBind();

之前执行此操作