Display a Nested List Inside Another Repeater
A simple way to display a list of data is to use an asp:Repeater. If the data also needs to show a nested list of related data for each main item, one can place another Repeater inside the first. In the code behind, the queries used for each Repeater can be linked in a dataset as a parent-child relationship via a Data Relation.
In the example below we make the multiple queries in only one SQL command statement, then link the result tables together by making a new DataRelation. The link uses key and foreign key ID columns from each result set.
This C# example shows how you can have a list of phone numbers as an area inside a larger list of contacts.
In the Page_Load function…
…
// Create and fill a DataSet
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT DISTINCT MemberID, Address, FirstName, LastName " +
" FROM MemberNames M; " +
"SELECT MemID, phonetype, Number " +
" FROM MemberNames M " +
" INNER JOIN Phone P ON M.MemberID = P.MemID;" +
, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds);
// Relate the two tables from the query together
ds.Relations.Add(new DataRelation("MemberID_Phone", ds.Tables[0].Columns["MemberID"], ds.Tables[1].Columns["MemID"]));
// Bind the outer Repeater to the DataSet.
rptMember.DataSource = ds.Tables[0];
rptMember.DataBind();
When we bind the data for each item in the outer Repeater, we will create a child view using the relation we linked previously.
protected void rptMember_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataRowView drv = e.Item.DataItem as DataRowView;
Repeater rptPhone = e.Item.FindControl("rptPhone") as Repeater;
rptPhone.DataSource = drv.CreateChildView("MemberID_Phone");
rptPhone.DataBind();
}
This snippet from the .aspx files shows the nested repeaters.
<asp:Repeater id="rptMember" OnItemDataBound="rptMember_ItemDataBound" runat="server">
<ItemTemplate>
<!– Tags to display the bound data (name, address, etc.) –>
<!– Make a repeater for all phone numbers for each person –>
<asp:Repeater id="rptPhone" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "PhoneType")%>:
<%# DataBinder.Eval(Container.DataItem, "Number")%>
</ItemTemplate>
</asp:Repeater>
…
To sum it all up, we implemented several technical elements here.
- Nested Repeaters
- Using a multi-result query
- Using DataSet Relations
Our example displays a list of Contacts with a sub-list for multiple phone numbers.