Click here to Skip to main content
Licence 
First Posted 18 Feb 2004
Views 214,564
Bookmarked 49 times

A Grouping Repeater Control for ASP.NET

By | 16 Sep 2004 | Article
This custom repeater control can be used to add group headers to your output.

Introduction

Have you ever wondered why ASP.NET did not come with a repeater control that can group results? Well, I did and I decided to try to write one myself.

I have seen other solutions to this problem, but not as simple and elegant as this one, and that is why I decided to share it.

Background

The Repeater control that comes with ASP.NET has one very cool event: the ItemCreated event. This event is fired whenever an element (or an instance of a template) is added to the Controls collection of the control.

Furthermore, the source demos in the ASP.NET SDK showed me how to use templates and data binding. Because it is documented in a lot of places on the web, I'm not going to repeat that here. Just hit Google with 'Templated Databound Control ASP.NET' and you'll see enough results.

The third part of the solution included the ability to provide a custom Comparer delegate that will compare 2 items of an unknown type.

The solution

What I did was the following:

  • Create a subclass of the System.Web.UI.WebControls.Repeater class.
  • Trap the ItemCreated event.
  • Add a GroupTemplate template to the control (in addition to the ItemTemplate).
  • For each item created, compare it to the previous item using a custom Comparer.
  • If it is different, instantiate the template and databind it using the same ItemData as the current Item.
  • Override the CreateChildControls method to reset the 'last record' member.

Anyway, I think this is a very good example of subclassing ASP.NET controls and I'm still wondering why this one isn't included in the standard framework.

Here's the code. It is also included in the demo solution file (see above).

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.ComponentModel;

namespace GroupedRepeater.Controls
{
 /// <summary>
 /// Summary description for GroupingRepeater.
 /// When another group is found, render an additional template.
 /// </summary>
 public class GroupingRepeater : System.Web.UI.WebControls.Repeater
 {
  private ITemplate _groupTemplate = null;
  private IComparer _comparer = null;
  private static object lastvalue = null;

  public GroupingRepeater()
  {
   this.ItemCreated += new 
     RepeaterItemEventHandler(GroupingRepeater_ItemCreated);
  }

  protected override void AddParsedSubObject(object obj)
  {
   base.AddParsedSubObject (obj);
  }

  public IComparer Comparer
  {
   get { return _comparer; }
   set { _comparer = value; }
  }

  [TemplateContainer(typeof(GroupHeader))]
  public ITemplate GroupTemplate
  {
   get 
   {
    return _groupTemplate; 
   }
   set 
   {
    _groupTemplate = value; 
   }
  }

  protected override void CreateChildControls()
  {
   lastvalue = null;
   base.CreateChildControls ();
  }

  private void GroupingRepeater_ItemCreated(object sender, 
                                      RepeaterItemEventArgs e)
  {
   System.Diagnostics.Trace.WriteLine(e.Item.GetType().Name);
   if(e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
   {
    if(e.Item.DataItem != null)
    {
     if(_comparer.Compare(lastvalue, e.Item.DataItem) != 0)
     {
      //add a header if it was different from the previous item.

      GroupHeader item = new GroupHeader();

      _groupTemplate.InstantiateIn(item);
      item.DataItem = e.Item.DataItem;
      this.Controls.Add(item);

      item.DataBind();
     }
    }
    lastvalue = e.Item.DataItem;
   }
  }

  public class GroupHeader : Control,INamingContainer
  {
   private object _dataItem;

   public virtual object DataItem 
   {
    get 
    {
     return _dataItem;
    }
    set 
    {
     _dataItem = value;
    }
   }
  }
 }
}

That's it! I hope you find this useful.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Rob van der Veer

Web Developer

Netherlands Netherlands

Member

Rob has been a professional web developer since 1998, and is working with C# and ASP.Net since early 2002.
 
Most of the time, his focus is on creating a clean and simple solution to development problems. (Although that sometimes means that he needs to do some hard work to make somebody else's life more easier.).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSimplier Control Code [modified] PinmemberMetalKid00710:34 31 Jul '09  
GeneralRe: Simplier Control Code Pinmembersuntereo14:19 16 Aug '10  
QuestionGroup by if category is not alphabettical PinmemberFiorina8116:13 27 May '09  
AnswerRe: Group by if category is not alphabettical PinmemberMetalKid00710:50 1 Aug '09  
NewsNot a control Pinmemberykorotia1:22 8 Nov '08  
Generalrepeater control customization Pinmemberkkwaghpriya20:43 5 Aug '08  
Generallastvalue not null when rebinding - ItemCommand doesn't fire Pinmembertpearl1970@hotmail.com11:16 18 Jul '08  
GeneralRe: lastvalue not null when rebinding - ItemCommand doesn't fire PinmemberRob van der Veer11:26 18 Jul '08  
GeneralRe: lastvalue not null when rebinding - ItemCommand doesn't fire PinmemberGiedriusBan1:39 3 Aug '09  
GeneralDifference in code sample / page code Pinmemberssdjspik4:16 21 Jul '05  
GeneralRe: Difference in code sample / page code Pinmemberuy_do4:35 19 May '06  
GeneralHelp needed rtying to make this work PinmemberROCNDAVE14:22 1 Jun '05  
This is exactly what I've been looking forn unfortunately I cant seem to get it working. I am new to ASP.Net and have a simple five column repeater control that I want grouped by the second column. I just cannot figure out how to make the download work as an example.
 
I am trying to copy and paste the code behind the forms and I get compile errors. Can someone help me with this?
GeneralDLL Pinmembergvkfaskljbvd10:16 18 May '05  
GeneralHaving Trouble Pinmemberdhainswo9:23 15 May '05  
GeneralItems.Count Pinmembercsstiffl11:31 20 Aug '04  
GeneralRe: Items.Count PinmemberRob van der Veer0:40 21 Aug '04  
GeneralRe: Items.Count PinmemberRob van der Veer23:02 16 Sep '04  
GeneralPostback converts GroupHeader to RepeaterItem Pinsussgninneh11:19 25 Jun '04  
GeneralRe: Postback converts GroupHeader to RepeaterItem PinmemberRob van der Veer11:45 12 Sep '04  
GeneralRe: Postback converts GroupHeader to RepeaterItem PinmemberRob van der Veer23:00 16 Sep '04  
Generalitemcommand problem Pinmemberjoecod8:33 1 Apr '04  
GeneralRe: itemcommand problem PinmemberRob van der Veer6:20 2 Apr '04  
GeneralRe: itemcommand problem Pinmemberjoecod22:36 4 Apr '04  
GeneralRe: itemcommand problem PinmemberRob van der Veer11:19 3 May '04  
GeneralRe: itemcommand problem PinsussAnonymous8:06 3 May '04  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120528.1 | Last Updated 16 Sep 2004
Article Copyright 2004 by Rob van der Veer
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid