title: Dynamically adding a user control to a repeater
body: <p>I have a class (MyClass) which represents a nested hierarchy, so the class has a property which is a collection of MyClass.  MyClass also has a title property</p>
  
  <p>To show it on a web page, I was hoping to create a user control which had a repeater. In the item template I would have literal to display the title property, and on the ItemCreated event of the repeater, I would create a new instance of the usercontrol, and add it into the current item in the repeater.</p>
  
  <p>My problem is, when the Page_Load event in the usercontrol fires, if the control was dynamically added, the repMyClass repeater poroperty is null, even if I call EnsureChildControls.  Am I missing something here?  If I create a repeater and drop my userctonrol in the item template it works fine. My can't I get this to work dynamically?</p>
  
  <p>User Control:</p>
  
  <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="MyControl" %&gt;
  Items:&lt;br/&gt;
  &lt;asp:Repeater ID="repMyClass" runat="server" EnableViewState="false" 
      OnItemCreated="repMenuItems_ItemCreated"&gt;
      &lt;HeaderTemplate&gt;&lt;ul&gt;&lt;HeaderTemplate&gt;
      &lt;ItemTemplate&gt;
          &lt;li&gt;&lt;%# Eval("Title") %&gt;
              &lt;div&gt;&lt;asp:PlaceHolder ID="SubItemPlaceholder" runat="server" /&gt;&lt;/div&gt;
          &lt;/li&gt;&lt;/ItemTemplate&gt;
      &lt;FooterTemplate&gt;&lt;/ul&gt;&lt;/FooterTemplate&gt;
  &lt;/asp:Repeater&gt;
  </code></pre>
  
  <p>User Control Code:</p>
  
  <pre><code>public partial class MyControl: System.Web.UI.UserControl
  {
      public IEnumerable&lt;MyClass&gt; ChildItems { get; set; }
      protected void Page_Load(object sender, EventArgs e)
      {
          this.repMyClass.DataSource = ChildItems;
          this.repMyClass.DataBind();
      }
  
      protected void repMenuItems_ItemCreated(object Sender, RepeaterItemEventArgs  e)
      {
          if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
          {
              //Get the MyClass instance for this repeater item
              MyClass mcCurrent = (MyClass)e.Item.DataItem;
  
              //If the MyClass instance has child instances
              if (mcCurrent.Children != null &amp;&amp; mcCurrent.Children.Length &gt; 0)
              {
                  //Add a new user control and set it's property so it can bind
                  PlaceHolder ph = (PlaceHolder)e.Item.FindControl("SubItemPlaceholder");
  
                  MyControl ctl = (MyControl)Page.LoadControl(typeof(MyControl),new object[] {});
  
                  ctl.ChildItems = mcCurrent.Children;
                  ph.Controls.Add(ctl);
              }
          }
      }
  }
  </code></pre>