-[Danny Chen]- Blog of an ASP.NET QA tester

Tips and info about Site Navigation, ImageMap, Menu and other cool ASP.NET v2.0 features.

Customizing Individual Menu Items

One question I see very frequently is how to customize the styles on an individual menu item. Declaratively, this isn't possible, although it is on the list of features for a future release. However, that doesn't mean it can't be done at all. It does take a little more work.  So, here are a couple variations on a theme to help customize various items. The ideas here can be extended on easily and I expect we might see some pretty interesting Menu's out there in the future.

Here's the most straight forward brute force way of setting an individual item style:

 <script runat="server">
Shared colorWheel As System.Collections.Generic.List(Of System.Drawing.Color)
Shared currentColor As System.Collections.Generic.List(Of System.Drawing.Color).Enumerator
Public Function GetBackColor() As System.Drawing.Color
   If colorWheel Is Nothing Then
      populatecolors()
   End If
   currentColor.MoveNext()
   Return currentColor.Current
End Function
Private Sub populatecolors()
   colorWheel =
New System.Collections.Generic.List(Of System.Drawing.Color)
   colorWheel.Add(Drawing.Color.Purple)
   colorWheel.Add(Drawing.Color.Green)
   colorWheel.Add(Drawing.Color.Brown)
   colorWheel.Add(Drawing.Color.Chartreuse)
   currentColor = colorWheel.GetEnumerator()
End Sub
</
script>

<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">

   <Items>

      <asp:MenuItem Text="one" Value="one"></asp:MenuItem>

      <asp:MenuItem Text="two" Value="two"></asp:MenuItem>

      <asp:MenuItem Text="three" Value="three"></asp:MenuItem>

      <asp:MenuItem Text="four" Value="four"></asp:MenuItem>

   </Items>

   <StaticItemTemplate>

      <asp:Label runat="server" ID="Label1" Text='<%# Eval("Text") %>'

         BackColor='<%# GetBackColor() %>' />

   </StaticItemTemplate>

</asp:Menu>

 

Now, this isn't the most ideal code for a number of reasons, but it gets the job done. So lets make 2 improvements. First, lets use the Style property so that we're not limited to a single style. Second, lets get away from relying on matching the order in our style list and the order of declared items.

<script runat="server">
Shared
styles As System.Collections.Generic.Dictionary(Of String, String)
Public Function GetStyle(ByVal value As String) As String
   If styles Is Nothing Then
      populateStyles()
   End If
   Return styles(value)
End Function
Private Sub populateStyles()
   styles =
New System.Collections.Generic.Dictionary(Of String, String)
   styles(
"one") = "background-color:Blue; color:White;"
   styles("two") = "background-color:Black; color:Yellow;"
   styles("three") = "background-color:Purple; color:Black;"
   styles("four") = "background-color:Green; color:Red;"
End Sub
</script>

<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">

   <Items>

      <asp:MenuItem Text="one" Value="one"></asp:MenuItem>

      <asp:MenuItem Text="two" Value="two">

         <asp:MenuItem Text="three" Value="three"></asp:MenuItem>

         <asp:MenuItem Text="four" Value="four"></asp:MenuItem>

      </asp:MenuItem>

   </Items>

   <StaticItemTemplate>

      <asp:Label runat="server" ID="Label1" Text='<%# Eval("Text") %>'

         Style='<%# GetStyle( Eval("Value") ) %>' />

   </StaticItemTemplate>

   <DynamicItemTemplate>

      <asp:Label runat="server" ID="Label1" Text='<%# Eval("Text") %>'

         Style='<%# GetStyle( Eval("Value") ) %>' />

   </DynamicItemTemplate>

</asp:Menu>

 

With this improvement, we have a lot control. Dynamic items also aren't a problem (although technically they weren't with the first method). With a bit of a variation, we can also make this work with a databound Menu like this:

 <script runat="server">
Shared styles As New System.Collections.Generic.Dictionary(Of String, String)
Protected Sub Menu1_MenuItemDataBound(ByVal sender As Object, _
                                      
ByVal e As System.Web.UI.WebControls.MenuEventArgs)
   styles(e.Item.ValuePath) =
CType(e.Item.DataItem, SiteMapNode)("style")
End Sub </script>
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"
   OnMenuItemDataBound="Menu1_MenuItemDataBound">
   <StaticItemTemplate>
      <asp:Label runat="server" ID="Label1" Text='<%# Eval("Text") %>'
         
Style='<%# styles( Eval("ValuePath") ) %>' />
   </StaticItemTemplate>
   <DynamicItemTemplate>
      <asp:Label runat="server" ID="Label1" Text='<%# Eval("Text") %>'
         
Style='<%# styles( Eval("ValuePath") ) %>' />
   </DynamicItemTemplate>
</asp:Menu>



[web.sitemap]
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
   <
siteMapNode url="root.aspx" title="root" style="">
      <
siteMapNode url="one.aspx" title="one" style="background-color:Blue; color:White;" />
      <
siteMapNode url="two.aspx" title="two" style="background-color:Black; color:Yellow;">
         <
siteMapNode url="three.aspx" title="three" style="background-color:Purple; color:Black;" />
         <
siteMapNode url="four.aspx" title="four" style="background-color:Green; color:Red;" />
      </
siteMapNode>
   </
siteMapNode>
</
siteMap>

Comments

Stefaan Rillaert said:

Hello Danny,

thanks for blogging, your posts help me to make better use of these controls you are working on as a QA tester. Still have a question though, a little bit connected with this post : Is there a way that we can customize the styles on individual tree nodes in the TreeView ? I ask this question because the TreeView doesn't support node templates (like the Menu control inheritance). Therefore I was looking into a solution that tries to add this to the TreeView by inheritance.

Since beta 2 the TreeView has become more extensible by adding the overridable function CreateNode() As TreeNode. This way someone can inherit from TreeView and change its behavior so that it uses a subclass that inherits from TreeNode instead of just instantiating default TreeNode(s).

However, when inheriting from TreeNode the only points where someone can change its appearance seems to be by overriding the RenderPreText and RenderPostText methods. This is great for adding stuff before or after the text of the tree node like checkboxes, images, etc. but it doesn't seem to help very much when one wants to change the style of the text of the tree node itself.

Even when one does something like :

Protected Overrides Sub RenderPreText(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.RenderPreText(writer)
writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "Grey")
End Sub

This results into an attribute 'style' with value "color:Grey;" being added to the hyperlink tag surrounding the text. But in IE this css-style is overridden by the css-styles defined in the 'class' attribute on the same (hyperlink) tag (in my test case class="TreeView1_0 TreeView1_1"). The css-styles in the 'class' attribute are defined by the server styles on the TreeView itself (NodeStyle, SelectedNodeStyle, …). So it are still these TreeView styles that decide the style of the node and not the css-styles added during RenderPreText.

Any ideas about how to inherit from the TreeView and getting styles on individual nodes working ?

Thanks in advance ! And enjoy Christmas and new year.

Stefaan
# December 21, 2005 8:20 AM

Stefaan Rillaert said:

To the readers of this blogentry :

I posted this question also on the asp.net forums (was quite impatient because the answer to this question meant the difference between creating a whole new custom treeview for our project or being able to inherit from the standard treeview) and Danny Chen was so kind enough to reply me over there (http://forums.asp.net/1152605/ShowPost.aspx). It seems that one can indeed adapt the style of individual TreeNodes. This will save a lot of time and effort. :)
# December 29, 2005 10:09 AM

Danny Chen said:

Thank you Stefaan for posting the follow up. The code he posted above actually does work. Call it a prototype; now that the model is set, it's a straight forward task to simply decide on the styles you want to provide, how to store them in your custom nodes, and add them to the rendering.
--
Danny
# December 29, 2005 11:53 AM

debasree said:

can you please provide a solution in C#?

# November 7, 2008 4:51 AM

Matt R said:

A much easier (but slightly ugly) way to do this is to escape an html tag into your menu item:

<asp:MenuItem Text="&lt;div style='color:darkblue;'&gt;Log Out&lt;/div&gt;" Value="5"></asp:MenuItem>

# November 5, 2009 10:04 AM

DD said:

hello Matt R,

Thanks for C# code but can you provide a easy code so that if we want some changes we can do easily.

# March 24, 2010 7:39 AM

Olga said:

Hello everyone. Hi, I have been here for several times now and thought to sign your guestbook. Very nice. Keep up the good work. Help me! I find sites on the topic: Las vegas eyelash extensions. I found only this - <a href="www.cis-cmc.eu/.../eyelash-extensions-langley">eyelash extensions langley</a>. Eyelash extensions, hairpiecethis area guards a fat order of mascara style colors, many as bald difference, issue eyelashes, accelerator, extensions, lashes, and girl eye. I am given in only listening out the chart about skincare and doing minutes live a 2005in cosmetic goodbye, eyelash extensions. With respect :o, Olga from Malaysia.

# March 24, 2010 2:38 PM

abilify said:

mood stabilizing and abilify

# August 8, 2010 3:40 PM

where said:

can I buy seroquel prioprity mail Arkansas

# August 11, 2010 7:42 PM

purchase said:

pentoxifylline amex fast delivery Louisiana

# August 21, 2010 11:45 PM

brand said:

low cost buspar jcb no rx canada

# August 21, 2010 11:45 PM

clozaril said:

need clozaril american express saturday delivery Oregon

# August 21, 2010 11:45 PM

cartia said:

purchase cartia cd in internet amex no script

# August 21, 2010 11:45 PM

triacet said:

buy triacet online saturday delivery Louisiana

# August 21, 2010 11:45 PM

augmentin said:

low cost augmentin shop without script Oregon

# August 21, 2010 11:45 PM

minocycline said:

best price minocycline no rx New York

# August 21, 2010 11:45 PM

loxapine said:

how to get loxapine online tab no rx Indiana

# August 21, 2010 11:45 PM

purchase said:

relafen online amex saturday delivery Connecticut

# August 21, 2010 11:45 PM

order said:

want to buy ursodiol (ursodeoxycholic) online canada

# August 21, 2010 11:45 PM

where said:

get urispas prioprity mail

# August 21, 2010 11:45 PM

online said:

how to buy allopurinol bp in internet fast

# August 21, 2010 11:45 PM

abuse said:

generic amantadine in internet western union Colorado

# August 21, 2010 11:45 PM

norethindrone said:

buy cod norethindrone in internet ach fedex

# August 21, 2010 11:45 PM

calcitriol said:

generic calcitriol online moneygram no rx

# August 21, 2010 11:45 PM

order said:

where to get crixivan shop saturday shipping Massachusetts

# August 25, 2010 4:10 AM

theox said:

theox cr overnight australia

# August 25, 2010 4:10 AM

order said:

want to buy theolair tr in internet check overnight

# August 25, 2010 4:10 AM

order said:

can I buy doxazosin online saturday shipping

# August 25, 2010 4:10 AM

nimotop said:

order nimotop prioprity mail

# August 25, 2010 4:10 AM

price said:

buy eskalith in internet pill fedex

# August 25, 2010 4:11 AM

purchase said:

buying maxalt non usa

# August 25, 2010 4:11 AM

effect said:

how to buy oxybutynin american express Louisiana

# August 25, 2010 4:11 AM

capoten said:

buy in online capoten online tabs

# August 25, 2010 4:11 AM

lariam said:

buying lariam online mastercard no script Idaho

# August 25, 2010 4:11 AM

brand said:

best price itraconazole online tabs prioprity mail South Carolina

# August 25, 2010 4:11 AM

cheap said:

where to buy isordil titradose tr cod accepted

# August 25, 2010 4:11 AM

price said:

buy in online clindamycin no script Louisiana

# August 27, 2010 12:55 PM

glucotrol said:

need glucotrol online discount saturday shipping

# August 27, 2010 12:56 PM

minocycline said:

low price minocycline tablets fast delivery Kansas

# August 27, 2010 12:56 PM

cataflam said:

buying cataflam online overnight Connecticut

# August 27, 2010 12:56 PM

online said:

low cost terazosin in internet check fedex

# August 27, 2010 12:56 PM

vytorin said:

effect vytorin in internet Georgia

# August 27, 2010 12:56 PM

order said:

loxapine ach greece

# August 27, 2010 12:56 PM

amantadine said:

abuse of amantadine in internet overnight West Virginia

# August 27, 2010 12:56 PM

trihexyphenidyl said:

to buy trihexyphenidyl in internet

# August 27, 2010 12:57 PM

Mary Swift said:

It was certainly interesting for me to read that article. Thank author for it. I like such themes and anything connected to them. I would like to read more on this site soon.    

Mary  Swift  

<a href="indianescortmodels.com/">london indian escorts</a>

# February 15, 2011 3:37 PM

Nicky Karver said:

It was certainly interesting for me to read that blog. Thank author for it. I like such topics and anything connected to them. I would like to read more on this site soon.    

Nicky  Karver    

<a href="www.latinescortlondon.com/">London spanish escort</a>

# February 23, 2011 5:50 PM

Mary Watcerson said:

It is rather interesting for me to read that blog. Thank author for it. I like such topics and anything connected to them. I would like to read more soon.      

Mary  Watcerson      

<a href="www.london-escort-agency.com/">west end escorts</a>

# March 9, 2011 8:30 PM

groping train said:

best for you, www.gravatar.com/gropingtraine groping train,  659,

# March 13, 2011 12:14 AM

new dumb blonde jokes said:

Your Site Is Great, www.gravatar.com/newdumbblondejokess Cheap new dumb blonde jokes,  =OO,

# March 13, 2011 9:05 AM

First airline discount student ticket said:

Is it so important?, www.crunchyroll.com/.../airlinediscountstuds First airline discount student ticket,  gifz,

# March 13, 2011 1:38 PM

very short skirts said:

Where it is possible to buy the, www.crunchyroll.com/.../veryshortskirtso very short skirts discount,  224034,

# March 13, 2011 2:19 PM

brutal dildo said:

I have the same., www.gravatar.com/brutaldildoi brutal dildo,  abad,

# March 13, 2011 3:20 PM

Discount groping train said:

Best Wishes!, www.crunchyroll.com/.../gropingtrains groping train for you,  641280,

# March 13, 2011 4:20 PM

Buy coeds need cash said:

So where it to find?, www.gravatar.com/coedsneedcashi coeds need cash online,  8O,

# March 13, 2011 8:00 PM

discount coach purses said:

:-(, www.gravatar.com/discountcoachpursess Only discount coach purses,  qadqbn,

# March 13, 2011 9:19 PM

Best panty pics said:

So where it to find, www.gravatar.com/pantypicss panty pics,  zpic,

# March 14, 2011 2:42 AM

latina ass said:

Beautiful site, www.crunchyroll.com/.../latinaassi latina ass,  :-[[[,

# March 14, 2011 3:02 AM

hot bikini girl price said:

Great, www.gravatar.com/hotbikinigirle First hot bikini girl,  691264,

# March 14, 2011 4:44 AM

Cheapest hallmark cards said:

Where it is possible to buy the, www.gravatar.com/hallmarkcardsa hallmark cards,  qtmj,

# March 14, 2011 7:28 AM

one year anniversary gift for boyfriend said:

Beautiful site, www.gravatar.com/oneyearanniversarygi Only one year anniversary gift for boyfriend,  :))),

# March 14, 2011 10:18 AM

coeds need cash said:

Beautiful site, www.crunchyroll.com/.../coedsneedcasha coeds need cash,  :-PP,

# March 14, 2011 10:40 AM

Buy marlboro cigarette coupons said:

What?, www.crunchyroll.com/.../marlborocigarettecoo Buy marlboro cigarette coupons,  jkeucy,

# March 14, 2011 3:08 PM

Nicky Swift said:

It was rather interesting for me to read this article. Thanks for it. I like such topics and everything that is connected to them. I definitely want to read more soon.        

Nicky  Swift      

<a href="rome-escort.info/">escort roma</a>

# March 15, 2011 6:53 PM

Mary Kripke said:

It was extremely interesting for me to read the blog. Thanx for it. I like such topics and everything that is connected to this matter. I would like to read more on this blog soon.        

Mary  Kripke        

<a href="www.phone-blocker.com/">jamming a cell phone</a>

# March 23, 2011 2:23 AM

Cheap knock off coach purses said:

:-), about.me/knockoffcoachpurses Cheap knock off coach purses,  192429,

# March 28, 2011 8:29 AM

Cheap debt settlement said:

Best Wishes!, http://about.me/debtsettlement debt settlement price,  :(,

# March 28, 2011 12:18 PM

First pay capital one credit card bill said:

:-), about.me/paycapitalonecreditcardbill pay capital one credit card bill for you,  slnk,

# March 28, 2011 1:03 PM

Discount diovan said:

I want to say thanks!, http://about.me/diovan diovan,  :-DDD,

# March 28, 2011 6:01 PM

Buy tax records copake new york said:

:-(, about.me/taxrecordscopakenewyork tax records copake new york,  888,

# March 28, 2011 10:34 PM

coach handbags said:

So where it to find, forums.naturalparenting.com.au/.../coachhandbags.html coach handbags,  rio,

# April 19, 2011 10:51 AM

Discount groping train said:

What?, forums.naturalparenting.com.au/.../gropingtrain.html Discount groping train,  955,

# April 19, 2011 12:51 PM

Sara Smith said:

It was certainly interesting for me to read that post. Thanks for it. I like such topics and anything connected to this matter. I would like to read more on this site soon.            

Sara  Smith            

<a href="monacoescort.com/">independent ladies escort in monaco</a>

# April 24, 2011 4:41 AM

Only very short shorts said:

Help me to find the, www.gravatar.com/tattoodesignsofzodio tattoo designs of zodiac signs price,  ujwh,

# June 26, 2011 5:42 AM

cool dress up games said:

What?, www.gravatar.com/littlegirlsdressupgo little girls dress up games online,  %-OO,

# June 26, 2011 6:56 AM

sissy dress for men said:

Beautiful site, www.gravatar.com/plussizeweddingdresa Discount plus size wedding dresses,  zvwqhr,

# June 26, 2011 7:39 AM

sissy forced galleries said:

Help me to find the, www.gravatar.com/miamiinktattoogallea miami ink tattoo gallery,  8-(,

# June 26, 2011 8:01 AM

Discount italian chicken recipes said:

Best, www.gravatar.com/pulledporkcrockpotrs pulled pork crockpot recipes,  ejdi,

# June 26, 2011 10:00 AM

Buy better business bureau florida said:

Only, www.gravatar.com/betterbusiness Buy better business bureau florida,  182,

# June 26, 2011 12:52 PM

leslies pool supplies discount said:

Beautiful site, www.gravatar.com/pooltournamene Discount pool tournament brackets,  fnnhl,

# June 27, 2011 1:23 AM

Cheap mini micro bikini said:

can you do thi for me, www.gravatar.com/microminiskira micro mini skirts online,  %-DDD,

# June 27, 2011 2:09 AM

girls in wet jeans online said:

What is it, www.gravatar.com/howtobraidalef how to braid a leather whip,  847,

# June 27, 2011 2:45 AM

leather motorcycle jackets said:

What?, www.gravatar.com/shortjokesforo short jokes for mobile phones price,  676932,

# June 27, 2011 3:08 AM

how to build a strawberry bed said:

Hi, www.gravatar.com/buildyourownsf build your own solar panel price,  8-OOO,

# June 27, 2011 5:49 AM

Only mossberg 500 accessories said:

Real, www.gravatar.com/pickuptruckack pickup truck accessories,  uwlk,

# June 27, 2011 6:47 AM

g string pics said:

What is it, www.gravatar.com/malibustringse malibu strings competition for you,  esl,

# June 27, 2011 6:59 AM

indiana jones costume said:

Best, www.gravatar.com/fancydresscostumese Best fancy dress costumes,  %)),

# June 27, 2011 12:33 PM

wooden pony discipline price said:

I like it so much, www.gravatar.com/woodenponydiscipline Only wooden pony discipline,  =]]],

# June 27, 2011 2:40 PM

what happens during a lap dance information said:

I want to say thanks!, www.gravatar.com/whatisatainti Cheapest what is a taint,  kqfrsr,

# June 27, 2011 4:14 PM

sports illiusrtated swim here said:

Best, www.gravatar.com/coloredcontactlensea colored contact lenses,  udhp,

# June 27, 2011 5:46 PM

glow in the dark contact lenses said:

Best Wishes, www.gravatar.com/glowinthedarkcontacs Cheapest glow in the dark contact lenses,  yzih,

# June 27, 2011 5:57 PM

Best iowa workforce development said:

can you do thi for me, www.gravatar.com/cheapsuperbowltickeo cheap super bowl tickets,  :[,

# June 27, 2011 6:20 PM

valentine heart clipart price said:

Real, www.gravatar.com/newyearscliparte new years clipart information,  84671,

# June 27, 2011 7:06 PM

skateboard decks price said:

Nice, www.gravatar.com/skateboardshopss skateboard shops information,  zkf,

# June 27, 2011 9:12 PM

cruise ship employment said:

Best Wishes, www.gravatar.com/norwegiancruiselineo norwegian cruise lines online,  78126,

# June 27, 2011 9:35 PM

office max locations now said:

Where it is possible to buy the, www.gravatar.com/steamyofficestorieso steamy office stories information,  hhh,

# June 27, 2011 10:56 PM

cheap office supplies information said:

Where it is possible to buy the, www.gravatar.com/orchardsupplyhardwai orchard supply hardware,  bva,

# June 28, 2011 12:27 AM

Alex said:

Have nice day! Much useful information, nice design, but this color hurts your eyes. 蒻

# July 27, 2011 9:23 PM

Yalin Meric said:

I have been struggling with asp menu styles for more than two days. When I used standard styles with fixed css values, the menu item css was suppressing the selected item css and making me crazy. At first I bumped to the rendering type of asp.menu and changed it to table so that the css's I defined were applied but this did not solve it. All I wanted was to apply a style for inactive items and another style for active one to emulate a tabbed control. At last I reached your approach which solved my problem forever. Thanks god I had a function that I had developed before to read styles from a css file located under my web project folder and return a style object. I added a new function based on that one to retunr the style text instead of a style object. Mission accomplished.

# September 13, 2011 9:31 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)