Nested Repeaters in ASP.NET

I’ve found that the simplest way to do nested repeaters without worrying about databinding events is to just set the DataSource using <%# %> syntax.

For example:

<asp:Repeater runat="server" id="Departments">
  <ItemTemplate>
    Name: <%# Eval("DeptName") %>
    Employees:
    <asp:Repeater runat="server" DataSource="<%# Eval("Employees") %>">
      <ItemTemplate><%# Eval("Name") %></ItemTemplate>
      <SeparatorTemplate>,</SeparatorTemplate>
    </asp:Repeater>
  </ItemTemplate>
</asp:Repeater>

This is presuming that your Departments class has an Employees property – eg:

public class Department {
  public string DeptName {get; set;}
  public IEnumerable<Employee> Employees {get; set;}
}
public class Employee {
  public string Name {get; set;}
}

If your outer-repeater object doesn’t have a property corresponding to the inner-repeater object you can still use this trick, by adding a method in your code-behind that does the calculation. So your inner repeater might become:

<asp:Repeater runat="server" DataSource="<%# GetEmployees(Container.DataItem) %>">

and then GetEmployees might look something like:

protected IEnumerable<Employee> GetEmployees(object item) {
  var dept = (Department) item;
  // then do whatever is necessary to get the employees from dept
  return employees;
}

Leave a Comment