user70192
user70192

Reputation: 14204

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,

Upvotes: 0

Views: 6847

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126804

<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
    }
}

Upvotes: 3

Lightweight
Lightweight

Reputation: 504

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

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415630

You need to use the repeater's OnItemDatabound event.

Upvotes: 0

Related Questions