Wednesday, May 10, 2006

Setting css styles on an individual MenuItem

It's been a while since I've written a tech post, but I think it's that time again. I've been working on a website for a potential client and came across an interesting problem with .NET 2.0 MenuItems (System.Web.UI.WebControls.MenuItem). Basically the website has a menu that displays a number of items, and one of the items should be bold. Now if you've played with the Menu control in .NET 2.0, you'll know that there are a lot of options for setting styles on menu items. However, I have yet to figure out a nice clean way to set a particular css style on only one item in the same level of a menu. Here is what I did do that seems to work, but I'd prefer a cleaner way so I'm all ears.

I started by defining my SiteMapNodes in the web.sitemap file, and was pleased to find out that I could add a custom attribute to the node that I could then call from code:


<sitemapnode title="My Page" description="" url="mypage.aspx" displaybold="true">

In the code I hooked into the MenuItemDataBound event of the Menu control, and added the following code:

SiteMapNode s = (SiteMapNode)e.Item.DataItem;
string displayBold = s["displaybold"];
if (displayBold != null && Convert.ToBoolean(displayBold) == true)
  e.Item.Text = "<div class=mycssclass>" + e.Item.Text + "</div>";

Now there are a few things to notice here. First of all, there is a nice clean way to fetch the custom attribute I added in the web.sitemap file. Using this I was hoping to selectively apply a css style to the menu items that corresponded to site map nodes with the displaybold=true attribute. Now this is where I ran into trouble. There is no class or style property on a MenuItem control. I did a fair amount of reading and research but could not find any mention about this. So I tried the code that is listed above, and to my surprise it works like a charm. All I needed to do now was hook up a stylesheet to the page this control rendered itself on, and ensure there was a class called mycssclass in there.

Like I said, I'd prefer to know of a cleaner way of doing this if there is one, since I particularly hate hard coding html into my codebehind files.

No comments: