Monday, June 15, 2009

ASP.Net Menu Control - Rounded Corners

So it's a little hard to play with ASP.Net's menu and there is no simple way to have tab with rounded corners unless you decide to do something with the render method of menu control, which is time consuming. And it doesn't help that menu item class is sealed and you can't do anything to it.

So here is this simple hack which will make the selected item's corner as image based, but with this simple trick, you can do alot of other creative things.

The whole idea is to set the selected item's text and you can specify any type of HTML using this!

Handle the menu's databound event and add the following code, as a side note, the HTML used here is not good and is not the suggested way of doing it, go for div based HTML with everything handled via CSS

protected void mainMenu_DataBound(object sender, EventArgs e)
{

if (!Page.IsPostBack)

if (mainMenu.SelectedItem != null)
{
MenuItem selectedItem = mainMenu.SelectedItem;

if (mainMenu.SelectedItem.Parent != null) //assuming two level menu
selectedItem = mainMenu.SelectedItem.Parent;

if (selectedItem != null)
{
string imgBg = "images/menubg.jpg";
string imgLeft = "images/menuleft.jpg";
string imgRight = "images/menuright.jpg";

_width = 240; //You may want to calculate it dynamically

selectedItem.Text = String.Format
(@"<table width='{5}' border='0' cellspacing='0' cellpadding='0'>
<tr>
<td width='6px' valign='top' background=''><img src='{1}' width='6' height='41' style='border:0px;' /></td>
<td width='{4}px' align='center' background='{2}' class='links'><div align='center'><strong>{0}</strong></div></td>
<td width='11px' valign='top'><img src='{3}' width='11' height='41' style='border:0px;' /></td>
</tr>
</table>", selectedItem.Text, imgLeft, imgBg, imgRight, _width, _width + 20);

}
}
}

Not the best solution out there, but it's definitely quick and dirty.

Update : As one of my friends just mentioned to me, apart from tables/div, you can also use JQuery to get rounded corners (which is actually the preferred approach these days,) but the approach of getting the rounded corner could be anything you want, using the selectedItem.Text property will allow you to set the Item's HTML according to your desire as you can't inherit MenuItem control and overwrite it's Render method.

No comments:

Post a Comment