title: Creating an ASP.NET Repeater Dynamically in C# Bound to an Object List
body: <p>I've got a very simple object:</p>
  
  <pre><code>public class DocumentType
  {
      private int id;
      private string name;
  
      public int ID
      {
          get { return this.id; }
          set { this.id = value; }
      }
  
      public string Name
      {
          get { return this.name; }
          set { this.name = value; }
      }
  }
  </code></pre>
  
  <p>I've got a list of DocumentType objects: <code>List&lt;DocumentType&gt; documentTypes = getDocuments();</code></p>
  
  <p>I'm working on a custom control where I'm trying to dynamically create a repeater and dynamically bind it to my object list.  Here's my code:</p>
  
  <pre><code>private Repeater docList;
  docList = new Repeater();
  docList.DataSource = documentTypes;
  docList.DataBind();
  
  foreach (RepeaterItem repeatItem in docList.Items)
  {
      // if condition to add HeaderTemplate Dynamically only Once
      if (repeatItem.ItemIndex == 0)
      {
          RepeaterItem headerItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Header);
          HtmlGenericControl hTag = new HtmlGenericControl("h4");
          hTag.InnerHtml = "Header";
          repeatItem.Controls.Add(hTag);
      }
  
      // Add ItemTemplate DataItems Dynamically
  
      RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);
      Label lbl = new Label();
  
      // This part is completely broken!
      lbl.Text = string.Format("Content: {0} {1} &lt;br /&gt;", (DocumentType)repeaterItem.DataItem).ID, repeaterItem.NamingContainer);
      repeatItem.Controls.Add(lbl);
  
      // Add SeparatorTemplate Dynamically
      repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Separator);
      LiteralControl ltrlHR = new LiteralControl();
      ltrlHR.Text = "&lt;hr /&gt;";
      repeatItem.Controls.Add(ltrlHR);
  }
  </code></pre>
  
  <p>The header and separator work great.  I can't figure out how to bind the item template to the current item to get it to display.  I know what I have in there right now is completely broken, but I've tried several variations with no luck.  </p>
  
  <p>Thanks in advance for any help or pointers in the right direction!</p>