ASP.NET Loading a User Control in a Repeater

I have a Repeater control that loads instances of a custom control I have built. This repeater looks like this:

<asp:Repeater ID="myRepeater" runat="server" OnLoad="myRepeater_Load">
  <HeaderTemplate>
    <table border="0" cellpadding="0" cellspacing="0">
  </HeaderTemplate>

  <ItemTemplate>
    <tr><td><my:CustomControl ID="myControl" runat="server" 
      OnLoad="myControl_Load" />
    </td></tr>
  </ItemTemplate>

  <FooterTemplate>
    </table>
  </FooterTemplate>
</asp:Repeater>

I bind to the Repeater through the myRepeater_Load event handler. My custom control is used to render an item within the Repeater. Because of this, I am trying to set properties on the custom control during the myControl_Load event handler. However, I do not know how to access the current item during the myControl_Load event.

Is there a way I can pass along the current item or access the current item during the myControl_Load event? If so, how?

Thank you,

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

<asp:Repeater ID="rptrDemo" runat="server" OnItemDataBound="rptrDemo_ItemDataBound">
    <ItemTemplate>
        <demo:Sample runat="server" ID="sampleControl" />
    </ItemTemplate>
</asp:Repeater>


protected void rptrDemo_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.DataItem != null)
    {
        SampleControl sampleControl = (SampleControl)e.Item.FindControl("sampleControl");
        // do whatever
    }
}

Solution 2

You need to use the repeater’s OnItemDatabound event.

Solution 3

use the OnItemDatabound event of the Repeater

        void r_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            CustomControl ctl = (CutonControl)e.Item.FindControl("myControl");
        }
    }

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply