Click here to Skip to main content
6,822,613 members and growing! (20,986 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.NET2.0, Win2K, WinXP, Win2003, Vista, ASP.NET, VS2005, Dev
Posted:6 Sep 2006
Updated:12 Sep 2006
Views:102,013
Bookmarked:87 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
32 votes for this article.
Popularity: 6.82 Rating: 4.53 out of 5
2 votes, 6.5%
1

2
1 vote, 3.2%
3
2 votes, 6.5%
4
26 votes, 83.9%
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


Member

Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular Custom Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 72 (Total in Forum: 72) (Refresh)FirstPrevNext
GeneralListBoxAdapter Pinmembervoleona13:51 1 Feb '10  
QuestionEvent validation errors PinmemberMember 446930410:00 17 Aug '09  
AnswerRe: Event validation errors PinmemberKishore.ssit22:31 7 Dec '09  
GeneralVB Version Pinmemberianbenoliel4:14 17 Feb '09  
QuestionUse of your code in VS2008 PinmemberMember 43782403:56 11 Feb '09  
AnswerRe: Use of your code in VS2008 Pinmemberlotuspro4:20 11 Feb '09  
AnswerRe: Use of your code in VS2008 PinmemberMember 43782405:29 11 Feb '09  
Generaloptgroup style change PinmemberJay K R19:51 8 Oct '08  
AnswerRe: optgroup style change PinmemberCaptainRantflaps0:24 13 Nov '08  
Questioncombination of ungroup item [modified] Pinmemberpaidinjav0:07 17 Sep '08  
AnswerRe: combination of ungroup item PinmemberMember 19547273:11 15 Dec '08  
Generaloptgroup structure disappears after PostBack PinmemberMember 37370024:30 2 Sep '08  
GeneralRe: optgroup structure disappears after PostBack PinmemberLamester14:51 17 Jun '09  
GeneralDrop Down list bind to sql server Pinmemberbismillah121:27 31 Aug '08  
General"OnSelectedIndexChanged" is not working. PinmemberMember 465139923:32 4 Aug '08  
GeneralRe: "OnSelectedIndexChanged" is not working. PinmemberSivaPrakasamDotNet23:34 16 Jul '09  
GeneralOnSelectedIndexChanged event not working PinmemberRashuD5:30 5 Feb '08  
GeneralRe: OnSelectedIndexChanged event not working PinmemberMember 465139921:20 11 Aug '08  
GeneralRe: OnSelectedIndexChanged event not working PinmemberSivaPrakasamDotNet0:33 17 Jul '09  
QuestionMore than one level??? Pinmemberlatiful1:33 8 Sep '07  
Generalchange of Font Style optgroup element Pinmemberaf_shamim14:01 23 Aug '07  
AnswerRe: change of Font Style optgroup element Pinmemberlotuspro0:06 24 Aug '07  
GeneralRe: change of Font Style optgroup element PinmemberNayeem Yahoo3:24 16 Jan '09  
GeneralUpdate to RenderContents PinmemberPedro Maia Costa2:05 20 Jul '07  
QuestionList get added again after postback Pinmemberxsoftdev6:20 19 Jul '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 12 Sep 2006
Editor: Smitha Vijayan
Copyright 2006 by lotuspro
Everything else Copyright © CodeProject, 1999-2010
Web17 | Advertise on the Code Project