Thursday, 22 January 2009

DropDownList with OptGroup support

Strangely guys from Microsoft did not implement (forgot???) support for optgroup tag in their standard DropDownList asp control so it's not possible to group items on the list.

Most of the workarounds found in Web suggest use of Control Adapter, like this one. However, there are couple things I don't like in this solution:
  • Doesn't work correctly when DataSource, AutoPostBack or OnSelectedIndexChanged attributes are set
  • Overrides regular regular behaviour & rendering of DropDownList items
  • Works for all DropDownList controls on the page (cannot be switched off for some lists)

Instead, I propose to create our own custom control that extends the standard DropDownList class. We need to override the method RenderContents inherited by DropDownList from System.Web.UI.WebControls.ListControl. When overriding it is very useful to base on original implementation so the default behaviour is preserved. To get the original RenderContents method's code you can use .NET Reflector:

So, your custom list control needs to look as follows:
namespace MyNamespace
public class MyList : System.Web.UI.WebControls.DropDownList
protected override void RenderContents(
System.Web.UI.HtmlTextWriter writer)
// Custom implementation goes here
Once you create your custom DropDownList you can use it on a page just like any other control. You only need to register it explicitly using following directive:
<%@ Register assembly="MyAssembly"
tagprefix="ma" %>
<ma:MyList ... />

Advantages of this appraoch:
  • Original behaviour is preserved.
  • You can use custom control only if you need grouping without affecting the rest of drop-downs on page
  • You can implement several custom drop downs with different customizations
  • Should work with AutoPostBack & OnSelectedIndexChanged
I've found sample implementation using this approach here and here.

No comments: