Click here to Skip to main content
11,642,855 members (75,667 online)
Click here to Skip to main content

ASP.NET DropDownList with OptionGroup support

, 12 Sep 2006 289.4K 5.9K 108
Rate this:
Please Sign up or sign in to vote.
An implementation of a DropDownList Control Adapter which provides OptionGroup support.

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

Share

About the Author

lotuspro
Web Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
NewsError while Try to run sample Pin
Dinesh Balaji24-Jun-14 3:26
memberDinesh Balaji24-Jun-14 3:26 
GeneralRe: Error while Try to run sample Pin
sfjaffer16-Sep-14 3:17
membersfjaffer16-Sep-14 3:17 
GeneralMy vote of 1 Pin
Member 100194966-Jun-14 5:15
memberMember 100194966-Jun-14 5:15 
SuggestionEnabling the code for listbox Pin
Michael Demeersseman24-Nov-13 21:24
memberMichael Demeersseman24-Nov-13 21:24 
QuestionIdeally you should include the code in a working Visual Studio Project Pin
liran bar niv24-Oct-13 10:14
memberliran bar niv24-Oct-13 10:14 
AnswerRe: Ideally you should include the code in a working Visual Studio Project Pin
PIEBALDconsult24-Oct-13 11:14
professionalPIEBALDconsult24-Oct-13 11:14 
Bugnot working Pin
bhawana13198918-Jul-12 19:02
memberbhawana13198918-Jul-12 19:02 
Suggestion&lt;optgroup&gt; support with ASP.net web componenets - An alternate way Pin
Shan Veerakutty12-Sep-11 9:55
memberShan Veerakutty12-Sep-11 9:55 
GeneralRe: <optgroup> support with ASP.net web componenets - An alternate way Pin
fengjunkuan20062-Jul-12 23:07
memberfengjunkuan20062-Jul-12 23:07 
GeneralRe: <optgroup> support with ASP.net web componenets - An alternate way Pin
yoursmuthu12-May-15 5:43
memberyoursmuthu12-May-15 5:43 
QuestionBinding data from Db Pin
sudheshna1235-Aug-11 20:46
membersudheshna1235-Aug-11 20:46 
GeneralCan you specific a license or terms or use... Pin
hhearst24-Apr-11 3:53
memberhhearst24-Apr-11 3:53 
GeneralRe: Can you specific a license or terms or use... Pin
lotuspro25-Apr-11 11:07
memberlotuspro25-Apr-11 11:07 
GeneralDropdowlist with optiongroup support using ajax Pin
Member 452360631-Aug-10 0:43
memberMember 452360631-Aug-10 0:43 
GeneralListBoxAdapter Pin
voleona1-Feb-10 12:51
membervoleona1-Feb-10 12:51 
QuestionEvent validation errors Pin
Member 446930417-Aug-09 9:00
memberMember 446930417-Aug-09 9:00 
AnswerRe: Event validation errors Pin
Kishore.ssit7-Dec-09 21:31
memberKishore.ssit7-Dec-09 21:31 
AnswerRe: Event validation errors Pin
Sean_ST2-Sep-10 11:55
memberSean_ST2-Sep-10 11:55 
GeneralRe: Event validation errors Pin
Member 392364420-Oct-10 17:18
memberMember 392364420-Oct-10 17:18 
GeneralVB Version Pin
ianbenoliel17-Feb-09 3:14
memberianbenoliel17-Feb-09 3:14 
QuestionUse of your code in VS2008 Pin
Member 437824011-Feb-09 2:56
memberMember 437824011-Feb-09 2:56 
AnswerRe: Use of your code in VS2008 Pin
lotuspro11-Feb-09 3:20
memberlotuspro11-Feb-09 3:20 
AnswerRe: Use of your code in VS2008 Pin
Member 437824011-Feb-09 4:29
memberMember 437824011-Feb-09 4:29 
Generaloptgroup style change Pin
Jay K R8-Oct-08 18:51
memberJay K R8-Oct-08 18:51 
AnswerRe: optgroup style change Pin
CaptainRantflaps12-Nov-08 23:24
memberCaptainRantflaps12-Nov-08 23:24 
Questioncombination of ungroup item [modified] Pin
paidinjav16-Sep-08 23:07
memberpaidinjav16-Sep-08 23:07 
AnswerRe: combination of ungroup item Pin
Member 195472715-Dec-08 2:11
memberMember 195472715-Dec-08 2:11 
GeneralRe: combination of ungroup item Pin
Sameers (theAngrycodeR )29-Mar-10 1:08
memberSameers (theAngrycodeR )29-Mar-10 1:08 
Generaloptgroup structure disappears after PostBack Pin
Member 37370022-Sep-08 3:30
memberMember 37370022-Sep-08 3:30 
GeneralRe: optgroup structure disappears after PostBack Pin
Lamester17-Jun-09 13:51
memberLamester17-Jun-09 13:51 
GeneralRe: optgroup structure disappears after PostBack Pin
Vipul12345626-Apr-10 19:57
memberVipul12345626-Apr-10 19:57 
GeneralRe: optgroup structure disappears after PostBack Pin
ridgie20-Jul-10 16:52
memberridgie20-Jul-10 16:52 
GeneralDrop Down list bind to sql server Pin
bismillah131-Aug-08 20:27
memberbismillah131-Aug-08 20:27 
GeneralOnSelectedIndexChanged event not working Pin
RashuD5-Feb-08 4:30
memberRashuD5-Feb-08 4:30 
GeneralRe: OnSelectedIndexChanged event not working Pin
Member 465139911-Aug-08 20:20
memberMember 465139911-Aug-08 20:20 
GeneralRe: OnSelectedIndexChanged event not working Pin
SivaPrakasamDotNet16-Jul-09 23:33
memberSivaPrakasamDotNet16-Jul-09 23:33 
GeneralRe: OnSelectedIndexChanged event not working Pin
Member 979468529-Jan-13 23:28
memberMember 979468529-Jan-13 23:28 
QuestionMore than one level??? Pin
latiful8-Sep-07 0:33
memberlatiful8-Sep-07 0:33 
Generalchange of Font Style optgroup element Pin
af_shamim23-Aug-07 13:01
memberaf_shamim23-Aug-07 13:01 
AnswerRe: change of Font Style optgroup element Pin
lotuspro23-Aug-07 23:06
memberlotuspro23-Aug-07 23:06 
GeneralRe: change of Font Style optgroup element Pin
Nayeem Yahoo16-Jan-09 2:24
memberNayeem Yahoo16-Jan-09 2:24 
GeneralRe: change of Font Style optgroup element Pin
GilesHinton2-Aug-10 5:46
memberGilesHinton2-Aug-10 5:46 
GeneralUpdate to RenderContents Pin
Pedro Maia Costa20-Jul-07 1:05
memberPedro Maia Costa20-Jul-07 1:05 
QuestionList get added again after postback Pin
xsoftdev19-Jul-07 5:20
memberxsoftdev19-Jul-07 5:20 
AnswerRe: List get added again after postback Pin
Pedro Maia Costa20-Jul-07 1:07
memberPedro Maia Costa20-Jul-07 1:07 
GeneralVB version anyone... Pin
jaywoncoder10-May-07 12:46
memberjaywoncoder10-May-07 12:46 
AnswerVB version with fixes below... Pin
WolfyUK20-Jun-07 5:38
memberWolfyUK20-Jun-07 5:38 
AnswerStandalone version [modified] Pin
Paul Appeldoorn4-Oct-07 3:53
memberPaul Appeldoorn4-Oct-07 3:53 
GeneralRe: Standalone version Pin
Member 437800431-Jul-08 20:18
memberMember 437800431-Jul-08 20:18 
QuestionRe: VB version with fixes below... [modified] Pin
CaptainRantflaps12-Nov-08 23:15
memberCaptainRantflaps12-Nov-08 23:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150731.1 | Last Updated 12 Sep 2006
Article Copyright 2006 by lotuspro
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid