Click here to Skip to main content
Licence 
First Posted 6 Sep 2006
Views 208,510
Bookmarked 102 times

ASP.NET DropDownList with OptionGroup support

By | 12 Sep 2006 | Article
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

About the Author

lotuspro

Web Developer

United Kingdom United Kingdom

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Suggestion<optgroup> support with ASP.net web componenets - An alternate way PinmemberShan Veerakutty9:55 12 Sep '11  
QuestionBinding data from Db Pinmembersudheshna12320:46 5 Aug '11  
GeneralCan you specific a license or terms or use... Pinmemberhhearst3:53 24 Apr '11  
GeneralRe: Can you specific a license or terms or use... Pinmemberlotuspro11:07 25 Apr '11  
GeneralDropdowlist with optiongroup support using ajax PinmemberMember 45236060:43 31 Aug '10  
GeneralListBoxAdapter Pinmembervoleona12:51 1 Feb '10  
QuestionEvent validation errors PinmemberMember 44693049:00 17 Aug '09  
AnswerRe: Event validation errors PinmemberKishore.ssit21:31 7 Dec '09  
AnswerRe: Event validation errors PinmemberSean_ST11:55 2 Sep '10  
GeneralRe: Event validation errors PinmemberMember 392364417:18 20 Oct '10  
GeneralVB Version Pinmemberianbenoliel3:14 17 Feb '09  
QuestionUse of your code in VS2008 PinmemberMember 43782402:56 11 Feb '09  
AnswerRe: Use of your code in VS2008 Pinmemberlotuspro3:20 11 Feb '09  
AnswerRe: Use of your code in VS2008 PinmemberMember 43782404:29 11 Feb '09  
Generaloptgroup style change PinmemberJay K R18:51 8 Oct '08  
AnswerRe: optgroup style change PinmemberCaptainRantflaps23:24 12 Nov '08  
Questioncombination of ungroup item [modified] Pinmemberpaidinjav23:07 16 Sep '08  
AnswerRe: combination of ungroup item PinmemberMember 19547272:11 15 Dec '08  
GeneralRe: combination of ungroup item PinmemberSameers (theAngrycodeR )1:08 29 Mar '10  
Generaloptgroup structure disappears after PostBack PinmemberMember 37370023:30 2 Sep '08  
I am using this adapter for listbox. Everything works fine except that optgroup structure disappears after PostBack. When I used following two functions for saving and loading viewstate it gives me error CS0115: 'ListAdapter.ListBoxAdapter.SaveViewState()': no suitable method found to override
 
The code I added for saving and loading viewstate is:
protected override object SaveViewState()
{
// Create an object array with one element for the CheckBoxList's
// ViewState contents, and one element for each ListItem in skmCheckBoxList
object[] state = new object[this.Items.Count + 1];
 
object baseState = base.SaveViewState();
state[0] = baseState;
 
// Now, see if we even need to save the view state
bool itemHasAttributes = false;
for (int i = 0; i < this.Items.Count; i++)
{
if (this.Items[i].Attributes.Count > 0)
{
itemHasAttributes = true;
 
// Create an array of the item's Attribute's keys and values
object[] attribKV = new object[this.Items[i].Attributes.Count * 2];
int k = 0;
foreach (string key in this.Items[i].Attributes.Keys)
{
attribKV[k++] = key;
attribKV[k++] = this.Items[i].Attributes[key];
}
 
state[i + 1] = attribKV;
}
}
 
// return either baseState or state, depending on whether or not
// any ListItems had attributes
if (itemHasAttributes)
return state;
else
return baseState;
}
 
protected override void LoadViewState(object savedState)
{
if (savedState == null) return;
 
// see if savedState is an object or object array
if (savedState is object[])
{
// we have an array of items with attributes
object[] state = (object[])savedState;
base.LoadViewState(state[0]); // load the base state
 
for (int i = 1; i < state.Length; i++)
{
if (state[i] != null)
{
// Load back in the attributes
object[] attribKV = (object[])state[i];
for (int k = 0; k < attribKV.Length; k += 2)
this.Items[i - 1].Attributes.Add(attribKV[k].ToString(), attribKV[k + 1].ToString());
}
}
}
else
// we have just the base state
base.LoadViewState(savedState);
}
 
Is there any complete solution for this?
GeneralRe: optgroup structure disappears after PostBack PinmemberLamester13:51 17 Jun '09  
GeneralRe: optgroup structure disappears after PostBack PinmemberVipul12345619:57 26 Apr '10  
GeneralRe: optgroup structure disappears after PostBack Pinmemberridgie16:52 20 Jul '10  
GeneralDrop Down list bind to sql server Pinmemberbismillah120:27 31 Aug '08  
General"OnSelectedIndexChanged" is not working. PinmemberMember 465139922:32 4 Aug '08  

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.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120604.1 | Last Updated 12 Sep 2006
Article Copyright 2006 by lotuspro
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid