Click here to Skip to main content
14,355,411 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

 
QuestionList get added again after postback Pin
xsoftdev19-Jul-07 6:20
memberxsoftdev19-Jul-07 6:20 
AnswerRe: List get added again after postback Pin
Pedro Maia Costa20-Jul-07 2:07
memberPedro Maia Costa20-Jul-07 2:07 
GeneralVB version anyone... Pin
jaywoncoder10-May-07 13:46
memberjaywoncoder10-May-07 13:46 
AnswerVB version with fixes below... Pin
WolfyUK20-Jun-07 6:38
memberWolfyUK20-Jun-07 6:38 
AnswerStandalone version [modified] Pin
Paul Appeldoorn4-Oct-07 4:53
memberPaul Appeldoorn4-Oct-07 4:53 
GeneralRe: Standalone version Pin
Member 437800431-Jul-08 21:18
memberMember 437800431-Jul-08 21:18 
QuestionRe: VB version with fixes below... [modified] Pin
CaptainRantflaps13-Nov-08 0:15
memberCaptainRantflaps13-Nov-08 0:15 
QuestionAjax [modified] Pin
davidprice3520-Mar-07 6:09
memberdavidprice3520-Mar-07 6:09 
QuestionCould Not Load Type 'DropDownListAdapter' Pin
tinybag1615-Mar-07 18:09
membertinybag1615-Mar-07 18:09 
AnswerRe: Could Not Load Type 'DropDownListAdapter' Pin
lotuspro16-Mar-07 2:50
memberlotuspro16-Mar-07 2:50 
AnswerRe: Could Not Load Type 'DropDownListAdapter' Pin
crockera12-Sep-07 0:57
membercrockera12-Sep-07 0:57 
AnswerRe: Could Not Load Type 'DropDownListAdapter' Pin
AndrewR736-Nov-07 9:56
memberAndrewR736-Nov-07 9:56 
QuestionOther browsers Pin
venetaibird18-Oct-06 20:06
membervenetaibird18-Oct-06 20:06 
AnswerRe: Other browsers Pin
lotuspro19-Oct-06 5:07
memberlotuspro19-Oct-06 5:07 
GeneralRe: Other browsers Pin
scott091215-Feb-07 5:55
memberscott091215-Feb-07 5:55 
AnswerRe: Other browsers Pin
lotuspro15-Feb-07 6:17
memberlotuspro15-Feb-07 6:17 
GeneralRe: Other browsers Pin
jnovax4-Jul-07 0:31
memberjnovax4-Jul-07 0:31 
QuestionenableEventValidation in PostBack ? Pin
itzikbs20-Sep-06 0:53
memberitzikbs20-Sep-06 0:53 
AnswerRe: enableEventValidation in PostBack ? [modified] Pin
Thxman25-Sep-06 4:16
memberThxman25-Sep-06 4:16 
GeneralRe: enableEventValidation in PostBack ? Pin
lotuspro25-Sep-06 23:18
memberlotuspro25-Sep-06 23:18 
GeneralRe: enableEventValidation in PostBack ? Pin
Thxman27-Sep-06 3:23
memberThxman27-Sep-06 3:23 
GeneralRe: enableEventValidation in PostBack ? Pin
wuxsh6-Sep-07 21:31
memberwuxsh6-Sep-07 21:31 
GeneralRe: enableEventValidation in PostBack ? Pin
Pawel Krakowiak26-Sep-07 1:26
memberPawel Krakowiak26-Sep-07 1:26 
Questionoptgroup structure disappears after PostBack Pin
oudoulj14-Sep-06 0:25
memberoudoulj14-Sep-06 0:25 
AnswerRe: optgroup structure disappears after PostBack Pin
lotuspro14-Sep-06 1:28
memberlotuspro14-Sep-06 1:28 

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.1K views
8K downloads
108 bookmarked