Search code examples
c#asp.netrepeaterweb-controls

How to add web user controls to repeater


Scenario:

  • UsrControl: custom user control, which contains a textbox and a button, rederend horizontally (in one line).

  • UsrControlContainer: custom user control, which should be able to display multiple UsrControl objects (each object in seperate line, so the Seperator template will probably be <br />. This control also contains a button, which adds new UsrControl to the collection.

My code:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
<asp:Repeater ID="rptExample" runat="server">
    <ItemTemplate>

    </ItemTemplate>
    <SeparatorTemplate><br /></SeparatorTemplate>
</asp:Repeater>

And:

protected void Button1_Click(object sender, EventArgs e)
{
    rptExample.DataSource = new List<UsrControl> {new UsrControl(), new UsrControl()};
    rptExample.DataBind();
}

Simple question - what should I put in ItemTemplate to make this work?

Edit - I also want to pass some parameters to UsrControl before rendering it.


Solution

  • <asp:Repeater ID="rptExample" runat="server">
         <ItemTemplate>
              <uc:UsrControl runat="server" />
         </ItemTemplate>
         <SeparatorTemplate><br /></SeparatorTemplate>
    </asp:Repeater>
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        rptExample.DataSource = Enumerable.Range(0, 2);
        rptExample.DataBind();
    }