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)
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 MyNamespaceOnce 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:
{
public class MyList : System.Web.UI.WebControls.DropDownList
{
protected override void RenderContents(
System.Web.UI.HtmlTextWriter writer)
{
// Custom implementation goes here
}
}
}
<%@ Register assembly="MyAssembly"
namespace="MyNamespace"
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
No comments:
Post a Comment