Click here to Skip to main content
6,292,426 members and growing! (10,527 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.NET 2.0, Win2K, WinXP, Win2003, Vista, ASP.NET, VS2005, Dev
Posted:6 Sep 2006
Updated:12 Sep 2006
Views:81,727
Bookmarked:78 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
29 votes for this article.
Popularity: 6.58 Rating: 4.50 out of 5
2 votes, 7.1%
1

2
1 vote, 3.6%
3
2 votes, 7.1%
4
23 votes, 82.1%
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 67 (Total in Forum: 67) (Refresh)FirstPrevNext
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  
GeneralOnSelectedIndexChanged event not working PinmemberRashuD5:30 5 Feb '08  
GeneralRe: OnSelectedIndexChanged event not working PinmemberMember 465139921:20 11 Aug '08  
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  
AnswerRe: List get added again after postback PinmemberPedro Maia Costa2:07 20 Jul '07  
GeneralVB version anyone... Pinmemberjaywoncoder13:46 10 May '07  
AnswerVB version with fixes below... PinmemberWolfyUK6:38 20 Jun '07  
AnswerStandalone version [modified] PinmemberPaul Appeldoorn4:53 4 Oct '07  
GeneralRe: Standalone version PinmemberMember 437800421:18 31 Jul '08  

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

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