Click here to Skip to main content
14,365,441 members

ASP.NET DropDownList with OptionGroup support

Rate this:
4.81 (39 votes)
Please Sign up or sign in to vote.
4.81 (39 votes)
12 Sep 2006
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

Comments and Discussions

 
QuestionThank You Pin
Member 421848814-Nov-16 2:52
memberMember 421848814-Nov-16 2:52 
QuestionMultiSelect DropdownList Using jQuery in Asp.Net MVC and C#.Net Pin
Member 123685433-Mar-16 19:42
memberMember 123685433-Mar-16 19:42 
QuestionUn-needed HTML in output... solution here. Pin
Sarah Cartwright29-Sep-15 2:23
memberSarah Cartwright29-Sep-15 2:23 
NewsError while Try to run sample Pin
Dinesh Balaji24-Jun-14 4:26
memberDinesh Balaji24-Jun-14 4:26 
GeneralRe: Error while Try to run sample Pin
sfjaffer16-Sep-14 4:17
membersfjaffer16-Sep-14 4:17 
GeneralMy vote of 1 Pin
Member 100194966-Jun-14 6:15
memberMember 100194966-Jun-14 6:15 
SuggestionEnabling the code for listbox Pin
Michael Demeersseman24-Nov-13 22:24
memberMichael Demeersseman24-Nov-13 22:24 
QuestionIdeally you should include the code in a working Visual Studio Project Pin
Best practice24-Oct-13 11:14
memberBest practice24-Oct-13 11:14 
AnswerRe: Ideally you should include the code in a working Visual Studio Project Pin
PIEBALDconsult24-Oct-13 12:14
protectorPIEBALDconsult24-Oct-13 12:14 
Bugnot working Pin
bhawana13198918-Jul-12 20:02
memberbhawana13198918-Jul-12 20:02 
Suggestion&lt;optgroup&gt; support with ASP.net web componenets - An alternate way Pin
Shan Veerakutty12-Sep-11 10:55
memberShan Veerakutty12-Sep-11 10:55 
GeneralRe: <optgroup> support with ASP.net web componenets - An alternate way Pin
fengjunkuan20063-Jul-12 0:07
memberfengjunkuan20063-Jul-12 0:07 
GeneralRe: <optgroup> support with ASP.net web componenets - An alternate way Pin
yoursmuthu12-May-15 6:43
memberyoursmuthu12-May-15 6:43 
QuestionBinding data from Db Pin
sudheshna1235-Aug-11 21:46
membersudheshna1235-Aug-11 21:46 
GeneralCan you specific a license or terms or use... Pin
hhearst24-Apr-11 4:53
memberhhearst24-Apr-11 4:53 
Hi,

This is a very useful function, however you did not specific any terms of use for it. This makes it difficult for me to use in my company. Could you please let me know if this example is under The Code Project Open License (CPOL) or some other license. Or can you specify terms under which I can use this code. Seem a shame you need to do this for a code examples website, but I don't make the rules. If you are still monitoring this article and can state this, I would be grateful.

Thanks much
-Hal
GeneralRe: Can you specific a license or terms or use... Pin
lotuspro25-Apr-11 12:07
memberlotuspro25-Apr-11 12:07 
GeneralDropdowlist with optiongroup support using ajax Pin
Member 452360631-Aug-10 1:43
memberMember 452360631-Aug-10 1:43 
GeneralListBoxAdapter Pin
voleona1-Feb-10 13:51
membervoleona1-Feb-10 13:51 
QuestionEvent validation errors Pin
Member 446930417-Aug-09 10:00
memberMember 446930417-Aug-09 10:00 
AnswerRe: Event validation errors Pin
Kishore.ssit7-Dec-09 22:31
memberKishore.ssit7-Dec-09 22:31 
AnswerRe: Event validation errors Pin
Sean_ST2-Sep-10 12:55
memberSean_ST2-Sep-10 12:55 
GeneralRe: Event validation errors Pin
FranklinL20-Oct-10 18:18
memberFranklinL20-Oct-10 18:18 
GeneralRe: Event validation errors Pin
teroni8-Jun-17 6:03
memberteroni8-Jun-17 6:03 
GeneralVB Version Pin
ianbenoliel17-Feb-09 4:14
memberianbenoliel17-Feb-09 4:14 
QuestionUse of your code in VS2008 Pin
Max Pace11-Feb-09 3:56
memberMax Pace11-Feb-09 3:56 

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

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

Article
Posted 6 Sep 2006

Stats

413.5K views
8K downloads
108 bookmarked