Click here to Skip to main content
15,891,529 members
Articles / Web Development / ASP.NET

A Hierarchical Repeater and Accessories to Match

Rate me:
Please Sign up or sign in to vote.
4.86/5 (10 votes)
1 Aug 2006CPOL4 min read 79.7K   635   35   25
A hierarchical Repeater control.

Introduction

I was working on a solution where there was a need to render sitemap data purely using DIVs. Upon initial coding, I tried to use the standard TreeView controls such as the ASP.NET TreeView and other third party controls. But none of them would allow for the custom rendering logic this project required. Most treeview or tree controls implement their own rendering logic that will break your design rules. Some times there is no "can't we just use what is available?", and when all else was exhausted, I just coded my way through it!!!! Nesting the Repeater would make sense, but coding this would get ugly since it was unknown how deep each tree was. Traversing the data in the Render method was the final solution taken. (Now try to get your HTML guy to fix the styling on that :-)).

After the solution was done, I decided to build a HierarchicalRepeater control using ASP.NET 2.0's HierarchicalDataBoundControl base class and allowing for total customization of the HTML styling and layout of hierarchical data, rather than the approach of overriding the Render method of the control used.

So I had my objective, but where to get started?

Here is a listing of problems that I wanted to solve in building this control:

  • Heck write my first CodeProject article.
  • Allow for complete control of the rendering logic in templates.
  • Ability to define multiple templates at each depth within a hierarchical structure.
  • Allow for DataBinding expressions:
  • ASP.NET
    <%#Eval("SomeProperty")%>
  • Create a hierarchical data structure using Generics that will allow a developer to define any object as a hierarchical using the IHierarchicalEnumerable and IHierarchyData interfaces.

The Structure of the HierarchicalRepeater Control

I started by defining a template infrastructure that will allow for hierarchical data to be iterated:

ASP.NET
<asp:SiteMapDataSource ID="SiteMapDataSource1" 
         runat="server" SiteMapProvider="MenuProvider" />
<cc1:HierarchicalRepeater runat="server" ID="repeater">
    <ItemHeaderTemplate><ul></ItemHeaderTemplate>
    <ItemTemplate><li><%#Eval("Title") %></li></ItemTemplate>
    <ItemFooterTemplate></ul></ItemFooterTemplate>
</cc1:HierarchicalRepeater>

Using this structure, I was able to create the following HTML:

Rendered output:
  • Home
    • Node1
      • Node1 1
      • Node1 2
      • Node1 3
    • Node2
      • Node2 1
      • Node2 2
      • Node2 3
    • Node3
      • Node3 1
      • Node3 2
      • Node3 3
      • Node3 4
        • Node3 4 1

The core function that allows this to happen is the CreateControlHierarchyRecursive method:

C#
protected virtual void CreateControlHierarchyRecursive(IHierarchicalEnumerable dataItems)

Hierarchical data sources rely on being able to iterate its nodes recursively. The HierarchicalRepeater achieves this by calling CreateControlHierarchyRecursive if there is a detection that the current data item has child items. This means that a full traversal of the data source is achievable.

But then I got to thinking, "Great, I have a HierarchicalRepeater control, but what about custom rendering styles per node depth?" With a little help from article's by Danny Chen, I followed his solution for creating a CustomTemplate and then wrapped that into a collection for use within the Repeater control. The ItemTemplate control allows you to specify at which depth and which ListItemType you would like to override. This helps when each depth has its own rendering logic, or the filtering renders specific depths when it is necessary to omit rendering of deep child nodes past a certain depth.

Hierarchical Repeater Control Using TemplateCollection

The following code renders a different color for each depth in a SiteMap. If you notice I have only one item footer template that will be used for all corresponding item templates.

Page code:
ASP.NET
<cc1:HierarchicalRepeater runat="server" 
                          ID="repeater" Width="231px">
    <TemplateCollection>
        <cc1:ItemTemplate Depth="0" ListItemType="ItemTemplate">
            <Template>
                <div style="padding-left:10px;border: 1px solid blue; background: blue;">
                <%#Eval("Item.Value") %>
            </Template>
        </cc1:ItemTemplate>
        <cc1:ItemTemplate Depth="1" ListItemType="ItemTemplate">
            <Template>
                <div style="padding-left:10px;border: 1px solid red; background: red;">
                <%#Eval("Item.Value") %>
            </Template>
        </cc1:ItemTemplate>
        <cc1:ItemTemplate Depth="2" ListItemType="ItemTemplate">
            <Template>
                <div style="padding-left:10px;border: 1px solid red; background: green;">
                <%#Eval("Item.Value") %>
            </Template>
        </cc1:ItemTemplate>
    </TemplateCollection>
    //Default ItemFooterTemplate used for all
    <ItemFooterTemplate>
        </div>
    </ItemFooterTemplate>
</cc1:HierarchicalRepeater>
Code-behind:
C#
HierarchyData<ListItem> root = 
         new HierarchyData<ListItem>(new ListItem("Root", "Root"), null);
HierarchyData<ListItem> child1 = 
         new HierarchyData<ListItem>(new ListItem("Child1", "child1"),root);
HierarchyData<ListItem> child2 = 
         new HierarchyData<ListItem>(new ListItem("Child2", "child2"),root);
HierarchyData<ListItem> child2_1 = 
         new HierarchyData<ListItem>(new ListItem("Child2_1", "child2_1"),child2);
HierarchyDataCollection<HierarchyData<ListItem>> coll = 
         new HierarchyDataCollection<HierarchyData<ListItem>>();
coll.Add(root);
repeater.DataSource = coll;
repeater.DataBind();

Rendered output of the control:

What is that Generic HierarchyData<T> in your code you ask?

There are only a few HierarchicalDatabound controls or classes that implement IHierarchicalEnumerable. Two notable controls are XMLDataSource and SiteMapDatasource, and a handful of classes that are used in conjunction with both datasource controls. Of course, since I am trying to sell you my HierarchicaRepeater control, it is only natural that I provide you with a mechanism for using your own objects to create hierarchical data, instead of you writing all the plumbing code for IHierarchyData and IHierarchicalEnumerable. Only after using Generics heavily for collections and lists did I realize how amazing Generics are. My attempt with the HierarchyData<T> is all the plumbing you need to start creating your own hierarchical datasources. So with HierarchicalRepeater and HierarchyData<T>, you are now ready to create and render complex hierarchical data sources with full control over the rendering of your data.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDatabinding HierarchyDataCollection to Treeview Pin
Larry R3-Jul-07 6:48
Larry R3-Jul-07 6:48 
Generalrepaired recursion and viewstate Pin
jwessel25-Jun-07 14:00
jwessel25-Jun-07 14:00 
GeneralRe: repaired recursion and viewstate Pin
Gary Vidal25-Jun-07 15:14
Gary Vidal25-Jun-07 15:14 
GeneralRe: repaired recursion and viewstate Pin
Andreas Kranister26-Jun-07 6:11
Andreas Kranister26-Jun-07 6:11 
GeneralRe: repaired recursion and viewstate Pin
jwessel26-Jun-07 6:53
jwessel26-Jun-07 6:53 
GeneralRe: repaired recursion and viewstate Pin
Andreas Kranister27-Jun-07 4:01
Andreas Kranister27-Jun-07 4:01 
GeneralRe: repaired recursion and viewstate Pin
Andreas Kranister27-Jun-07 4:12
Andreas Kranister27-Jun-07 4:12 
GeneralRe: repaired recursion and viewstate Pin
acl12323-Oct-08 14:12
acl12323-Oct-08 14:12 
Thanks for your efforts on this control guys - it works really well now.

I made a couple of changes to the Hierarchical Repeater. The main difference is that I call OnItemDataBound for ItemHeaderTemplate and ItemFooterTemplate. I think this should be fine - I use this sometimes to change the item's header or footer based on the data. Just be sure to check the ItemType during ItemDataBound handlers.

Also the object code used a class called "List" which is not part of the .NET framework. I changed this to "List<object>".

    [DefaultEvent("ItemCommand"), DefaultProperty("DataSource"), ParseChildren(true), PersistChildren(false)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [ToolboxData("<{0}:HierarchicalRepeater runat="server">")]
    public class HierarchicalRepeater : HierarchicalDataBoundControl, INamingContainer
    {
        private ItemTemplateCollection myTemplateList = new ItemTemplateCollection();
        private ITemplate myHeaderTemplate;
        private ITemplate myFooterTemplate;
        private ITemplate myItemTemplate;
        private ITemplate myItemHeaderTemplate;
        private ITemplate myItemFooterTemplate;
        private List<object> myItemArray;
        private List<object> myItems;
        private DataSourceSelectArguments myArguments;


        public event HierarchicalRepeaterCommandEventHandler ItemCommand;
        public event HierarchicalRepeaterItemEventHandler ItemDataBound;
        public event HierarchicalRepeaterItemEventHandler ItemCreated;


        [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(IDataItemContainer))]
        public ItemTemplateCollection TemplateCollection
        {
            get
            {
                return myTemplateList;
            }
            set
            {
                myTemplateList = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(IDataItemContainer))]
        public ITemplate HeaderTemplate
        {
            get
            {
                return myHeaderTemplate;
            }
            set
            {
                myHeaderTemplate = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(IDataItemContainer))]
        public ITemplate FooterTemplate
        {
            get
            {
                return myFooterTemplate;
            }
            set
            {
                myFooterTemplate = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(IDataItemContainer))]
        public ITemplate ItemTemplate
        {
            get
            {
                return myItemTemplate;
            }
            set
            {
                myItemTemplate = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(IDataItemContainer))]
        public ITemplate ItemHeaderTemplate
        {
            get
            {
                return myItemHeaderTemplate;
            }
            set
            {
                myItemHeaderTemplate = value;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(IDataItemContainer))]
        public ITemplate ItemFooterTemplate
        {
            get
            {
                return myItemFooterTemplate;
            }
            set
            {
                myItemFooterTemplate = value;
            }
        }

        public List<object> Items
        {
            get
            {
                if (myItems == null)
                {
                    if (myItemArray == null)
                        EnsureChildControls();

                    if (myItemArray == null)
                        throw new NullReferenceException("Item Array was not created during CreateChildControls.");

                    myItems = new List<object>(myItemArray);
                }

                return myItems;
            }
        }

        protected DataSourceSelectArguments SelectArguments
        {
            get
            {
                if (myArguments == null)
                    myArguments = DataSourceSelectArguments.Empty;

                return myArguments;
            }
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }


        protected override void PerformDataBinding()
        {
            Controls.Clear();
            ClearChildViewState();
            CreateControlHierarchy(true);
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            if (ViewState["itemGraph"] != null)
                CreateControlHierarchy(false);
        }

        protected override bool OnBubbleEvent(object source, EventArgs e)
        {
            HierarchicalRepeaterCommandEventArgs e2 = e as HierarchicalRepeaterCommandEventArgs;
            if (e2 != null)
            {
                OnItemCommand(e2);
                return true;
            }
            return false;
        }

        protected virtual void CreateControlHierarchy(bool useDataSource)
        {
            myItemArray = new List<object>();
            if (useDataSource)
            {
                CreateControlHierarchyRecursive(GetData("").Select(), 0);

                StringBuilder sb = new StringBuilder();
                foreach (HierarchicalRepeaterItem item in myItemArray)
                {
                    if (item.ItemType == HierarchicalListItemType.Header)
                        sb.Append("H");
                    else if (item.ItemType == HierarchicalListItemType.ItemHeader)
                        sb.Append("h");
                    else if (item.ItemType == HierarchicalListItemType.Item)
                        sb.Append("i");
                    else if (item.ItemType == HierarchicalListItemType.ItemFooter)
                        sb.Append("f");
                    else if (item.ItemType == HierarchicalListItemType.Footer)
                        sb.Append("F");
                }

                ViewState["itemGraph"] = sb.ToString();
            }
            else
            {
                int depth = -1;
                int dataItemIndex = 0;
                int displayIndex = 0;
                string itemGraph = (string)ViewState["itemGraph"];

                HierarchicalRepeaterItem repeaterItem = null;
                foreach (char c in itemGraph)
                {
                    switch (c)
                    {
                        case ('H'):
                            repeaterItem = new HierarchicalRepeaterItem(0, displayIndex++, ++depth, HierarchicalListItemType.Header);
                            break;
                        case ('h'):
                            repeaterItem = new HierarchicalRepeaterItem(0, displayIndex++, depth, HierarchicalListItemType.ItemHeader);
                            break;
                        case ('i'):
                            repeaterItem = new HierarchicalRepeaterItem(dataItemIndex++, displayIndex++, depth, HierarchicalListItemType.Item);
                            break;
                        case ('f'):
                            repeaterItem = new HierarchicalRepeaterItem(0, displayIndex++, depth, HierarchicalListItemType.ItemFooter);
                            break;
                        case ('F'):
                            repeaterItem = new HierarchicalRepeaterItem(0, displayIndex++, depth--, HierarchicalListItemType.Footer);
                            break;
                    }

                    InitializeItem(repeaterItem);
                    Controls.Add(repeaterItem);
                }
            }
            ChildControlsCreated = true;
        }

        protected virtual void CreateControlHierarchyRecursive(IHierarchicalEnumerable enumerable, int depth)
        {
            int dataIndex = 0;
            int displayIndex = 0;

            HierarchicalRepeaterItem header = CreateItem(-1, displayIndex++, depth, HierarchicalListItemType.Header, null, false);
            myItemArray.Add(header);

            foreach (IHierarchyData data in enumerable)
            {
                HierarchicalRepeaterItem itemHeader = CreateItem(-1, displayIndex++, depth, HierarchicalListItemType.ItemHeader, data, true);
                myItemArray.Add(itemHeader);

                HierarchicalRepeaterItem item = CreateItem(dataIndex++, displayIndex++, depth, HierarchicalListItemType.Item, data, true);
                myItemArray.Add(item);

                if (data.HasChildren)
                    CreateControlHierarchyRecursive(data.GetChildren(), depth + 1);

                HierarchicalRepeaterItem itemFooter = CreateItem(-1, displayIndex++, depth, HierarchicalListItemType.ItemFooter, data, true);
                myItemArray.Add(itemFooter);
            }

            HierarchicalRepeaterItem footer = CreateItem(-1, displayIndex, depth, HierarchicalListItemType.Footer, null, false);
            myItemArray.Add(footer);
        }

        protected virtual HierarchicalRepeaterItem CreateItem(int dataItemIndex, int displayIndex, int depth, HierarchicalListItemType itemType, object dataItem, bool dataBind)
        {
            HierarchicalRepeaterItem repeaterItem = new HierarchicalRepeaterItem(dataItemIndex, displayIndex, depth, itemType);
            InitializeItem(repeaterItem);
            Controls.Add(repeaterItem);

            HierarchicalRepeaterItemEventArgs e = new HierarchicalRepeaterItemEventArgs(repeaterItem);
            OnItemCreated(e);

            if (dataBind)
            {
                repeaterItem.DataItem = dataItem;
                repeaterItem.DataBind();
                OnItemDataBound(e);
            }

            return repeaterItem;
        }

        protected virtual void InitializeItem(HierarchicalRepeaterItem item)
        {
            System.Diagnostics.Debug.WriteLine(item.DisplayIndex);
            ITemplate template = TemplateCollection.GetTemplate(item.Depth, item.ItemType);

            if (template == null)
            {
                if (item.ItemType == HierarchicalListItemType.Header)
                    template = myHeaderTemplate;
                else if (item.ItemType == HierarchicalListItemType.Footer)
                    template = myFooterTemplate;
                else if (item.ItemType == HierarchicalListItemType.ItemHeader)
                    template = myItemHeaderTemplate;
                else if (item.ItemType == HierarchicalListItemType.ItemFooter)
                    template = myItemFooterTemplate;
                else if (item.ItemType == HierarchicalListItemType.Item)
                    template = myItemTemplate;
                else
                    throw new ApplicationException("Invalid ItemType");
            }

            if (template != null)
                template.InstantiateIn(item);
        }

        protected virtual void OnItemCommand(HierarchicalRepeaterCommandEventArgs e)
        {
            if (ItemCommand != null)
                ItemCommand(this, e);
        }

        protected virtual void OnItemDataBound(HierarchicalRepeaterItemEventArgs e)
        {
            if (ItemDataBound != null)
                ItemDataBound(this, e);
        }

        protected virtual void OnItemCreated(HierarchicalRepeaterItemEventArgs e)
        {
            if (ItemCreated != null)
                ItemCreated(this, e);
        }
    }
</object></object></object></object></object>

QuestionViewState does not work? Pin
Andreas Kranister19-Jun-07 1:20
Andreas Kranister19-Jun-07 1:20 
AnswerRe: ViewState does not work? Pin
Gary Vidal21-Jun-07 16:14
Gary Vidal21-Jun-07 16:14 
GeneralRe: ViewState does not work? [modified] Pin
Andreas Kranister21-Jun-07 20:22
Andreas Kranister21-Jun-07 20:22 
AnswerRe: ViewState does not work? Pin
Gary Vidal21-Jun-07 16:27
Gary Vidal21-Jun-07 16:27 
NewsRe: ViewState does not work? Pin
Andreas Kranister21-Jun-07 20:12
Andreas Kranister21-Jun-07 20:12 
AnswerRe: ViewState does not work? Pin
jwessel25-Jun-07 9:57
jwessel25-Jun-07 9:57 
GeneralRe: ViewState does not work? Pin
Member 11601363-Jul-08 8:29
Member 11601363-Jul-08 8:29 
GeneralQuestion: Pin
EarlLocker6-May-07 6:32
EarlLocker6-May-07 6:32 
QuestionItemHeaderTemplate and ItemFooterTemplate Pin
rsenna17-Sep-06 12:30
rsenna17-Sep-06 12:30 
AnswerRe: ItemHeaderTemplate and ItemFooterTemplate [modified] Pin
Gary Vidal17-Sep-06 19:02
Gary Vidal17-Sep-06 19:02 
GeneralRe: ItemHeaderTemplate and ItemFooterTemplate Pin
rsenna18-Sep-06 4:59
rsenna18-Sep-06 4:59 
GeneralRe: ItemHeaderTemplate and ItemFooterTemplate Pin
jwessel25-Jun-07 11:22
jwessel25-Jun-07 11:22 
GeneralRe: ItemHeaderTemplate and ItemFooterTemplate Pin
jwessel25-Jun-07 11:30
jwessel25-Jun-07 11:30 
GeneralThanks Pin
wduros12-Aug-06 10:12
wduros12-Aug-06 10:12 
GeneralRe: Thanks Pin
Gary Vidal2-Aug-06 14:07
Gary Vidal2-Aug-06 14:07 
GeneralDLinq and your control [modified] Pin
Orizz26-Jul-06 5:17
Orizz26-Jul-06 5:17 
GeneralRe: DLinq and your control Pin
Gary Vidal26-Jul-06 12:24
Gary Vidal26-Jul-06 12:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.