In search of an easy way to use nested repeaters

by Mikael Henriksson 27. January 2009 18:59

I was searching around on the net for a way to display Hierarchical Data with nested repeaters. Found some quite extensive ways to solve this simple problem. Then someone (sorry for not remembering the url) had come up with a much easier way of doing this.

I'll start with the way I want it displayed

To acomplish this I first need 2 repeaters.

<asp:Repeater Runat="server" ID="_itemsRepeater" EnableViewState="false">
	<ItemTemplate>
		<asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
		<asp:Repeater 
			 Runat="server" ID="_subitemsRepeater" EnableViewState="false" 
			 DataSource='<%# DataBinder.Eval(Container.DataItem, "SubItems") %>'>
			 
			<ItemTemplate>
				<br/>
				<asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
			</ItemTemplate>

		</asp:Repeater>
		<br/>
	</ItemTemplate>
</asp:Repeater>

As you can see, nothing fancy so far. The real trick comes in code behind. First step is to databind the repeaters and here is where it gets beautiful!

protected void Page_Load(object sender, EventArgs e)   
{
	_itemsRepeater.DataSource = ItemsBLL.GetData();
	_itemsRepeater.DataBind();
}
   
public class ItemsBLL
{
	public static IList<Item> GetData()
	{
		IList<Item> itemList = new List<Item>();
		for (int i = 0; i < 10; i++) 
		{
			Item _item = new Item("item" + i.ToString());
			for (int j = 0; j < 5; j++)
			{
				Item subItem = new Item("subitem" + j.ToString());
				_item.SubItems.Add(subItem);
			}
			
			itemList.Add(_item);
		}
		
		return itemList;
	}
}


public class Item
{
	string _name;
	IList<Item> _subItems = new List<Item>();
	
	public Item(string name) { _name = name; }
	public string Name { get { return _name; } }  

	public IList<Item> SubItems { get { return _subItems; } }
}

See how I only have to bind this one time, the business layer does the rest. No recursive lists bindning to both of the repeaters. keeping it REAL simple for the UI programmer. In this case the UI programmer is myself really but I still find it very useful and less clutter in the codebehind of the aspx page. I admit this is probably not an ideal solution if you need all the extras with keeping separate lists for recursive functions or sorting etc. I just needed something simple this time.

Tags:

ASP.NET

blog comments powered by Disqus

About the author

Life architect specialized in programming