5,446,542 members and growing! (18,946 online)
Email Password   helpLost your password?
Web Development » Custom Controls » General     Intermediate

ASP.NET DropDownList with OptionGroup support

By lotuspro

An implementation of a DropDownList Control Adapter which provides OptionGroup support.
C# 2.0, C#Windows, .NET, .NET 2.0, Win2K, WinXP, Win2003, Vista, ASP.NET, VS2005, Visual Studio, Dev

Posted: 6 Sep 2006
Updated: 12 Sep 2006
Views: 58,567
Bookmarked: 66 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
27 votes for this Article.
Popularity: 6.40 Rating: 4.47 out of 5
2 votes, 7.7%
1
0 votes, 0.0%
2
1 vote, 3.8%
3
2 votes, 7.7%
4
21 votes, 80.8%
5

Introduction

ASP.NET 2.0, for all its bells and whistles, lacks the odd bit of functionality for reasons completely unknown. One such notable omission is that of OptionGroup (<optgroup>) support in the DropDownList control. For those unfamiliar with the <optgroup> element, it is part of the XHTML standard, and has the effect of categorising items in a <select>, as the following image shows.

Option Groups

When I first began to look for a solution to implement this in ASP.NET, I found very few articles on the topic that offered any viable solution. Another CodeProject member came up with a nice clean solution, but it looked like a lot of code and I was convinced there was an easier way. After reading some comments, it became apparent a Control Adapter was the way to go. Control Adapters are new in ASP.NET 2.0, and allow the developer to override the rendering behaviour of any control, very powerful stuff! Furthermore, Control Adapters are used in conjunction with a browser file, so specific browsers may be targeted, if required. Armed with that knowledge, the solution became simple. The attached download contains the requisite files to implement this solution in your own projects, but for posterity, I paste it here also.

public class DropDownListAdapter : 
       System.Web.UI.WebControls.Adapters.WebControlAdapter {
    protected override void RenderContents(HtmlTextWriter writer) {
        DropDownList list = this.Control as DropDownList;
        string currentOptionGroup;
        List<string> renderedOptionGroups = new List<string>();
        foreach(ListItem item in list.Items) {
            if(item.Attributes["OptionGroup"] == null) {
                RenderListItem(item, writer);
            } else {
                currentOptionGroup = item.Attributes["OptionGroup"];
                if(renderedOptionGroups.Contains(currentOptionGroup)) {
                    RenderListItem(item, writer);
                } else {
                    if(renderedOptionGroups.Count > 0) {
                        RenderOptionGroupEndTag(writer);
                    }
                    RenderOptionGroupBeginTag(currentOptionGroup, 
                                              writer);
                    renderedOptionGroups.Add(currentOptionGroup);
                    RenderListItem(item, writer);
                }
            }
        }
        if(renderedOptionGroups.Count > 0) {
            RenderOptionGroupEndTag(writer);
        }
    }
    private void RenderOptionGroupBeginTag(string name, 
                 HtmlTextWriter writer) {
        writer.WriteBeginTag("optgroup");
        writer.WriteAttribute("label", name);
        writer.Write(HtmlTextWriter.TagRightChar);
        writer.WriteLine();
    }
    private void RenderOptionGroupEndTag(HtmlTextWriter writer) {
        writer.WriteEndTag("optgroup");
        writer.WriteLine();
    }
    private void RenderListItem(ListItem item, 
                 HtmlTextWriter writer) {
        writer.WriteBeginTag("option");
        writer.WriteAttribute("value", item.Value, true);
        if(item.Selected) {
            writer.WriteAttribute("selected", "selected", false);
        }
        foreach(string key in item.Attributes.Keys) {
            writer.WriteAttribute(key, item.Attributes[key]);
        }
        writer.Write(HtmlTextWriter.TagRightChar);
        HttpUtility.HtmlEncode(item.Text, writer);
        writer.WriteEndTag("option");
        writer.WriteLine();
    }
}

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

lotuspro



Occupation: Web Developer
Location: Canada Canada

Other popular Custom Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
Subject  Author Date 
Generaloptgroup structure disappears after PostBackmemberMember 37370024:30 2 Sep '08  
GeneralDrop Down list bind to sql servermemberbismillah121:27 31 Aug '08  
General"OnSelectedIndexChanged" is not working.memberMember 465139923:32 4 Aug '08  
GeneralOnSelectedIndexChanged event not workingmemberRashuD5:30 5 Feb '08  
GeneralRe: OnSelectedIndexChanged event not workingmemberMember 465139921:20 11 Aug '08  
QuestionMore than one level???memberlatiful1:33 8 Sep '07  
Generalchange of Font Style optgroup elementmemberaf_shamim14:01 23 Aug '07  
AnswerRe: change of Font Style optgroup elementmemberlotuspro0:06 24 Aug '07  
GeneralUpdate to RenderContentsmemberPedro Maia Costa2:05 20 Jul '07  
QuestionList get added again after postbackmemberxsoftdev6:20 19 Jul '07  
AnswerRe: List get added again after postbackmemberPedro Maia Costa2:07 20 Jul '07  
GeneralVB version anyone...memberjaywoncoder13:46 10 May '07  
AnswerVB version with fixes below...memberWolfyUK6:38 20 Jun '07  
AnswerStandalone version [modified]memberPaul Appeldoorn4:53 4 Oct '07  
GeneralRe: Standalone versionmemberMember 437800421:18 31 Jul '08  
QuestionAjax [modified]memberdavidprice356:09 20 Mar '07  
QuestionCould Not Load Type 'DropDownListAdapter'membertinybag1618:09 15 Mar '07  
AnswerRe: Could Not Load Type 'DropDownListAdapter'memberlotuspro2:50 16 Mar '07  
AnswerRe: Could Not Load Type 'DropDownListAdapter'membercrockera0:57 12 Sep '07  
AnswerRe: Could Not Load Type 'DropDownListAdapter'memberAndrewR739:56 6 Nov '07  
QuestionOther browsersmembervenetaibird20:06 18 Oct '06  
AnswerRe: Other browsersmemberlotuspro5:07 19 Oct '06  
GeneralRe: Other browsersmemberscott09125:55 15 Feb '07  
Answer