Programming Without Walls
Software Engineering with Microsoft .net

Implementing OptGroup In A DropDownList Control

June 6, 2008 by Bob Barth

As I promised in the previous post, I will detail how to implement the HTML <optgroup> tag inside a <select> tag in this post. The HTML markup looks as follows when using the optgroup tag:

   1: <select>
   2:     <optgroup label="Group 1">
   3:         <option>Item 1</option>
   4:         <option>Item 2</option>
   5:         <option>Item 3</option>
   6:     </optgroup>
   7:     <optgroup label="Group 2">
   8:         <option>Item 4</option>
   9:         <option>Item 5</option>
  10:         <option>Item 6</option>
  11:         <option>Item 7</option>
  12: </optgroup>

That code would render something like the following:

optgroupexample

As you can see, the optgroup tags render as bold and italicized group labels (that cannot be selected), and the items under each are indented. Note that in IE the optgroup tags cannot be styled but FireFox does permit styling.

As we know, the select tag is implemented in .net as the DropDownList control. At render time, the control renders <option> tags from its Items collection. At first glance, it would seem like all one has to do to subclass the control and add an OptionGroups collection property which is a collection of ListItems (the type of the standard Items property). While this is part of what needs to be done, it is only the beginning.

Adding Option Groups

To start off, obviously we must create a class that inherits from DropDownList. I called this control OptionGroupDropDownList. Next, we need to add something to hold the optgroup tags. I added an OptionGroups property to the control:

   1: public OptionGroupCollection OptionGroups
   2: {
   3:     get
   4:     {
   5:         if (_optionGroups == null)
   6:         {
   7:             _optionGroups = new OptionGroupCollection();
   8:             if (_isTrackingViewState)
   9:                 _optionGroups.TrackViewState();
  10:         }
  11:  
  12:         return _optionGroups;
  13:     }
  14: }

As you can see, the OptionGroups property is of type OptionGroupCollection. Two helper classes are required to implement this control: the aforementioned OptionGroupCollection and OptionGroup. Additionally, some state management things are going on in the property get accessor (there's no need for a set accessor). The state management is the thing that complicates this control beyond a simple subclass and render override that the UnEncodedDropDownList was. You'll see why we need to manage state in a moment.

OptionGroupCollection And OptionGroup Classes

To make things easy, OptionGroupCollection is simply a wrapper around a List<OptionGroup> private member. The OptionGroup is a couple of properties necessary to implement the optgroup tag and a wrapper for a ListItemCollection, which is a collection of the ListItems (option tags) that will render inside the optgroup tag. This is where the state management comes in. To make it easy for the user I wanted the items inside each OptionGroup to look and behave the same as the items in a normal DropDownList so I used the same class the built-in control uses: ListItemCollection. However, because ListItemCollection (and the ListItem child objects) are sealed, it is somewhat more cumbersome to manage the state of items in this collection than it would be otherwise. Luckily, ListItemCollection implements the IStateManager interface, which we will use to tell it when to manage its own state and obtain a state object.

State Management

To correctly manage state, the OptionGroupDropDownList control must manually manage its own state by overriding all of the IStateManager methods of the base DropDownList control, most important among them being TrackViewState:

   1: protected override void TrackViewState()
   2: {
   3:     base.TrackViewState();
   4:     this.OptionGroups.TrackViewState();
   5:     _isTrackingViewState = true;
   6: }

TrackingViewState signals the control (and any child controls that also need to know via manual forwarding) to start tracking viewstate. Without this signal, the ListItemCollection would never save its state between server round-trips. OptionGroupCollection and OptionGroup both implement IStateManager and therefore TrackViewState.

Two other important methods to override in the OptionGroupDropDownList (with regard to state management) are SaveViewState and LoadViewState. This is because the OptionGroupsCollection's state needs to be saved and loaded (which, in turn, saves the OptionGroup's, which in turn saves the ListItemCollection's state, which in turn saves the individual ListItem's state - it's just a chain and each individual object is responsible for saving its own state as an object and returning that object in SaveViewState). This is what these two method overrides look like:

   1: protected override object SaveViewState()
   2: {
   3:     return new Pair(base.SaveViewState(), _optionGroups.SaveViewState());
   4: }
   5:  
   6: protected override void LoadViewState(object savedState)
   7: {
   8:     Pair viewState = (Pair)savedState;
   9:  
  10:     base.LoadViewState(viewState.First);
  11:     this.OptionGroups.LoadViewState(viewState.Second);
  12: }

Rendering

The last important method to override is the RenderContents method which actually renders out our new OptionGroup items. This method is not very complicated and simply iterates the OptionGroups and OptionGroup.Items:

   1: protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
   2: {
   3:     if (this.OptionGroups.Count > 0)
   4:         foreach (OptionGroup optionGroup in this.OptionGroups)
   5:         {
   6:             writer.AddAttribute("label", optionGroup.LabelText);
   7:             optionGroup.LabelStyle.AddAttributesToRender(writer);
   8:             writer.RenderBeginTag("optgroup");
   9:  
  10:             foreach (ListItem item in optionGroup.Items)
  11:             {
  12:                 if (item.Enabled)
  13:                 {
  14:                     if (item.Selected)
  15:                         writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected");
  16:  
  17:                     writer.AddAttribute(HtmlTextWriterAttribute.Value, item.Value);
  18:  
  19:                     if (item.Attributes != null && item.Attributes.Count > 0)
  20:                         item.Attributes.Render(writer);
  21:  
  22:                     if (this.Page != null)
  23:                         this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);
  24:  
  25:                     writer.RenderBeginTag("option");
  26:                     writer.Write(item.Text);
  27:                     writer.RenderEndTag();
  28:                 }
  29:             }
  30:  
  31:             writer.RenderEndTag();
  32:         }
  33:     else
  34:         base.RenderContents(writer);
  35: }

Use

To use the control simply add OptionGroups and items to the OptionGroups you create:

   1: OptionGroupDropDownList ogdMain = new OptionGroupDropDownList();
   2:  
   3: OptionGroup group = ogdMain.OptionGroups.Add("Group 1");
   4: group.Items.Add("Item 1");
   5: group.Items.Add("Item 2");
   6: group.Items.Add("Item 3");
   7:  
   8: group = ogdMain.OptionGroups.Add("Group 2");
   9: group.Items.Add("Item 4");
  10: group.Items.Add("Item 5");
  11: group.Items.Add("Item 6");
  12: group.Items.Add("Item 7");
  13:  
  14: Page.Controls.Add(ogdMain);

Of course, you can declare the control on the aspx page; I have created it here programmatically just so the code runs if you copy and paste.

This control works just fine inside an AJAX UpdatePanel, in case you're wondering. There are some other incidentals with dealing with post data, which you can check out in the code, linked below.

Conclusion/Caveats

This was an interesting control to implement as I had to do a bunch of spelunking using Reflector to figure out how ListItemCollection saves state. It permits me to use the optgroup tag in a select tag, which is not exactly a requirement very often, but it's one of those things that when you need it, you need it.

Of course there are caveats: The default Items collection is not rendered in any way. I didn't need both at the same time so I didn't implement it. You can, however, change the code however you like. You'll want to mess about in the RenderContents method. Additionally, not a whole lot of testing has been done. I know, as I stated above, that this control works with an AJAX postback just perfectly, however, I'm not exactly sure how it works with regular postbacks. Most likely it works fine since the AJAX scenario is more complicated, but I make no guarantees.

OptionGroupDropDownList.cs (7.29 kb)

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

March 3, 2009 5:31 AM

vaji

Hello,
Nice article.
I have a question, how to add an element to an optGroup?
I am able to add an element as option but it is listed in the end of the list. But my requirement is to add an element in optGroup.
For example

In your example I want to add an item called "Item N" to the OptGroup "Group 1".
How to do that?

vaji

August 14, 2009 9:54 AM

Alex

Hi,

I'm new to .net. May I know how to declare it in aspx page?

Thanks for sharing.

Alex

August 25, 2009 8:57 AM

Jairam

I owe you one. Thanks a lot

Jairam

October 10, 2009 3:46 PM

r00t

thanks good article

r00t

October 30, 2009 7:57 AM

cash loans

I always wanted to write in my site something like that but I guess you'r faster Smile

cash loans

November 3, 2009 3:39 AM

free casino games

Really i am impressed from this post....the person who create this post he is a great human..thanks for shared this with us.i found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article

free casino games

November 6, 2009 3:09 AM

book keeping company

Hi,

Why did the FIA just abandon the further look into the Mclaren 2008 car?

book keeping company

November 10, 2009 4:26 AM

SEO

How can we count that how many items in a dropdown list using java script?

SEO

November 14, 2009 3:00 AM

payday loans

I like what I see. keep it going

payday loans

November 23, 2009 2:44 AM

on line poker websites

The default Items collection is not rendered in any way. I didn't need both at the same time so I didn't implement it. You can, however, change the code however you like. You'll want to mess about in the RenderContents method. Additionally, not a whole lot of testing has been done

on line poker websites

November 25, 2009 10:29 PM

Life insurance

What is a dropdown menu and how do you use it?

Life insurance

November 26, 2009 6:14 AM

instant messenger software

So far, I managed to go though only some of posts you discuss here, but I find them very interesting and informative. Just want say thank you for the information you have shared. Regards

instant messenger software

November 26, 2009 9:40 PM

david mandy

Great,it is admirable what you have done here. It is fabulous to see you verbalize from the heart and your clarity on this significant subject can be easily seen.Fantastic post and will look forward to your incoming update

david mandy

November 27, 2009 7:20 AM

online free games

Hi webmaster, nice blog post. Please continue this great work!!!!

online free games

November 29, 2009 5:32 AM

youdoodolls

Doing a little research. specific aided me – thank you. Nettie Chalmers ~ pocketpeople

youdoodolls

November 29, 2009 6:52 PM

800 Vanity Numbers

In most cases I do not make comments on blogs, but I want to say that this post really forced me to do so. Really nice post!

800 Vanity Numbers

November 30, 2009 1:25 AM

Income protection insurance

How can we count that how many items in a drop down list using java script?

Income protection insurance

November 30, 2009 3:02 PM

reverse number lookup

After searching for this information, I will have to say most people agree with you on this topic.

reverse number lookup

December 1, 2009 5:24 AM

online poker strategy

This looks great. Just a thought though, any chance this could be combined with the cascading combobox concept?
Say for athletics meet, first choose the disciplines offered (track, field BUT not raod) then the events based on this selection ([100m, 200m BUT not 1000m] , [javelin, shotput]) etc

online poker strategy

December 1, 2009 7:17 AM

Eva Zacker

Usually I do not post on articles, but I would like to say that this article really forced me to do so! Thanks, really nice blog.

Eva Zacker

December 1, 2009 7:48 AM

marquee brisbane

# Tax advantages. Different structures are treated differently in tax law, and may have advantages for this reason.

marquee brisbane

December 3, 2009 7:07 AM

personalized gift

Thank you for sharing another beneficial piece of information. Regards, Susie Brown @ personalizedgifts

personalized gift

December 3, 2009 6:35 PM

proxy sites

Keep up the good work bro.Your article is really great and I truly enjoyed reading it.Waiting for some more great articles like this from you in the coming days.

proxy sites

December 4, 2009 3:51 AM

antivirus firewall

How are programming languages different from conventional languages?

antivirus firewall

December 5, 2009 7:41 PM

Marion

Intimately, the post is in reality the sweetest on this worthy topic. I concur with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be adequate, for the fantastic clarity in your writing. I will at once grab your rss feed to stay privy of any updates. Fabulous work and much success in your business endeavors!

Marion

December 5, 2009 7:58 PM

payday loans

Of course, what a great site and advisory posts, Can I add backlink - import your rss feed? Regards, Reader.

payday loans

December 6, 2009 10:40 AM

payday loans

good good…this post deserves nothing Frown …hahaha just joking Tong …nice post Tong

payday loans

December 6, 2009 1:15 PM

Chara Flicker

Hi could anyone tell me their thoughts on a good download torrent service. What paid service would you recommend?

Chara Flicker

December 6, 2009 2:22 PM

unibet

Very interesting clock.. I really love reading this articles.

unibet

December 6, 2009 3:15 PM

Manuela Benes

A nicely written piece, informative, coherent and intelligently put forward, respect due for a welcome relief from the usual dross I find on the internet, I will be watching out for more of your posts.

Manuela Benes

December 6, 2009 7:59 PM

Gary Reynolds

The writing here are great. Thanks for having them. I love reading other sites about web site marketing! It's such an exciting topic. I don't comment on many web sites but had to on yours. I don't have time to read everything here right now, I found your site while looking for something else on ask.com. But I've bookmarked your homepage and will visit it regularly to read what's new. I love reading web sites about affiliate marketing. It's such an exciting topic. <a href="http://www.linkthe.com">Visit my site if you'd like to read more</a>. Thanks again for a very educational site!

Gary Reynolds

December 8, 2009 8:01 AM

Bastien

Well, the post is really the sweetest on this notable topic. I agree with your conclusions and will eagerly look forward to your coming updates. Just saying thanks will not just be sufficient, for the exceptional clarity in your writing. I will immediately grab your rss feed to stay privy of any updates. Gratifying work and much success in yourbusiness dealings!

Bastien

December 8, 2009 9:11 AM

resveratrol capsules

Hey! I admire your writing and the way you explain things. Some of the comments on here too are insightful. I appreciate you. keep it up! John from http://resveratroleffects.org .

resveratrol capsules

December 9, 2009 6:16 PM

casino en ligne

Considerably, the post is in reality the freshest on this worthy topic. I harmonise with your conclusions and will eagerly look forward to your forthcoming updates. Just saying thanks will not just be adequate, for the great lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Authentic work and much success in yourbusiness enterprize!

casino en ligne

December 10, 2009 5:09 AM

faxless payday loans

Just try to smile for about 2-3 mins then you can get back to work

faxless payday loans

December 10, 2009 3:29 PM

personalized gift

Very entertaining post. Harriet Wilson ~ tinypocketpeple

personalized gift

December 11, 2009 3:23 PM

auto accident attorney ma

I have firefox at home computer but right now I'm at friends house and browsing your site&nbsp;with Internet Explorer&nbsp;adn everything is messed up. Anyone here also is running into this problem or is it&nbsp;just me?

auto accident attorney ma

December 12, 2009 1:01 AM

Memory Foam Topper

is the theme you using free?

Memory Foam Topper

December 12, 2009 3:43 PM

colon cleansers

Such a wonderful thought. There is nothing else to add other than to acknowledge a job well done. can you show how to grab your rss feed? I couldn't find how.

colon cleansers

December 13, 2009 5:56 AM

Shonda Jacobs

I would like to thank you for the efforts you have made in composing this article. I am going for the same best work from you in the future as well. In fact your fanciful writing abilities has prompted me to start my own blog now. Actually the blogging is spreading its wings rapidly. Your write up is a fine example of it.

Shonda Jacobs

December 13, 2009 8:48 PM

safe weight loss

I just wanted to add a comment here to say thanks for you very nice ideas. Blogs are troublesome to run and time consuming thus I appreciate when I see well writen material. Your time is not going to waste with your posts. Thanks so much and keep on No doubt you will defintely reach your goals! cheers!

safe weight loss

December 14, 2009 9:29 AM

fast personal loans

Wow and wow! Thank you! I always wished to write in my site something like that.

fast personal loans

December 14, 2009 10:20 AM

HEEL PADS

thanks for this interesting information I have post a link on my site so my friends can benefit from it too.

HEEL PADS

December 14, 2009 5:26 PM

The Lion King

I know this is really boring and you are skipping to the next comment, but I just wanted to throw you a big thanks - you cleared up some things for me!

The Lion King

December 15, 2009 11:23 AM

herpes treatment

Considerably, the article is in reality the greatest on this worthw hile topic. I concur with your conclusions and will thirstily look forward to your coming updates. Saying thanks will not just be enough, for the great lucidity in your writing. I will at once grab your rss feed to stay informed of any updates. Gratifying work and much success in your business efforts!

herpes treatment

December 15, 2009 3:45 PM

BUY HEEL CUPS

thank you for this valuable information I must post a link on my blog so my subscribers can benefit from it also.

BUY HEEL CUPS

December 16, 2009 12:46 AM

auto insurance quote

Which form is used to show capital gain for filing Income tax?

auto insurance quote

December 16, 2009 2:22 AM

wow quest helper kid

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

wow quest helper kid

December 16, 2009 7:21 PM

best Insulated Water Bottles

Comfortabl y, the article is really the best on this deserving topic. I fit in with your conclusions and will thirstily look forward to your next updates. Just saying thanks will not just be sufficient, for the tremendous clarity in your writing. I will at once grab your rss feed to stay abreast of any updates. Fabulous work and much success in your business enterprize!

best Insulated Water Bottles

December 16, 2009 7:59 PM

Rob Smith

did you make this site yourself?

Rob Smith

December 17, 2009 4:54 AM

James Harvey

I agree with you.Good post. I like your blog and have already bookmarked

James Harvey

December 17, 2009 6:39 AM

Pulqui Menchaca

Hi, maybe this post is not on topic but in any case, I have been surfing about your blog and it looks very great. It is apparent that you know your subject matter and you are passionate about it. I am creating a new blog and I am hard-pressed to make it look great, and offer excellent articles. I have discovered a much here and I look forward to more updates and will be coming back soon.

Pulqui Menchaca

December 17, 2009 5:56 PM

Backlink Secret

Doing some web surfing and noticed your blog appears a bit messed up in my K-meleon internet browser. But fortunately hardly anyone uses it any longer but you may want to look into it.

Backlink Secret

December 17, 2009 9:09 PM

Sandra

In most occassions I don’t post on blogs, but I want to mention that this post really forced me to do so. Really nice post!

Sandra

December 18, 2009 10:19 AM

Micahel

Howdy, I arrived at this site by on accident when I was searching on Google then I came onto your website. I must say your website is cool I just love the theme! don’t possess the time at the moment to fully read through your website web sitebut I have bookmarked it. I will come back in a day or two. Thanks for a great site.

Micahel

December 18, 2009 9:03 PM

Adam

In general I don’t make comments on blogs, but I have to say that this post really forced me to do so. Really nice post!

Adam

December 19, 2009 7:38 AM

pet meds

This is good site to spent time on .I just stumbled upon your informative blog and wanted to say that I have really enjoyed reading your very well written blog posts. I will be your frequent visitor, that’s for sure.

pet meds

December 19, 2009 7:24 PM

Skin Today

I thought I would leave my first comment, Thank you and I will want to read more from you.

Skin Today

December 19, 2009 8:43 PM

online payroll

Generally I don’t post on blogs, but I have to mention that this post really forced me to do so. Really nice post!

online payroll

December 20, 2009 8:39 AM

Hookah Pipe

trying to figure out your rss feeds...how do u set it up?

Hookah Pipe

December 20, 2009 3:56 PM

sam sean

hey, your post&nbsp;really assists, today i happen the same problems, and i donot know how to figure out the problem. finanlly i search yahoo and discovered your post, it helps me get rid of my trouble.
thanks againjust one thing, can i paste your entry on my blog? i will add the source.regards!

sam sean

December 20, 2009 4:50 PM

faxing from pc

I read your blog every once in a while and I just have to mention that I like your template!

faxing from pc

December 20, 2009 5:22 PM

Jessica Okamoto

I heard there is a fun solitaire game. My close friend showed me it, and I really think it's the best solitaire game ever made! I got it here: <a href="http://www.funsolitairegame.com/">Get" rel="nofollow">http://www.funsolitairegame.com/">Get The Solitaire Game</a> http://www.funsolitairegame.com/

Jessica Okamoto

December 21, 2009 1:54 AM

usa online casinos

Dude.. I am not much into reading, but somehow I got to read lots of articles on your blog. Its amazing how interesting it is for me to visit you very often.

usa online casinos

December 21, 2009 5:04 AM

autism early signs

I have never been so grateful for providing me with such interesting fact on the most duscussable points.

autism early signs

December 21, 2009 5:45 AM

cromalinsupport

Have a question about this? This site/article is all about providing you all the information you've been hunting for.

cromalinsupport

December 21, 2009 6:15 AM

cpcentercity.com

What makes this so interesting is the developments taking place. We've brought together all the relevant information here for you.

cpcentercity.com