I have two ASP.NET Menu controls on a page.
One in my header (tabs) for top level pages, e.g. ~/Default.aspx
And one in my sidebar for sub pages, e
My menu isn't databound so MenuItemDataBound is never fired. Below is my solution to highlight the parent menu item when there are child items and when there are not:
Add a StaticSelectedStyle-xxx to the Menu, like StaticSelectedStyle-BackColor="#757588"
Call this method on Page_Load:
protected void SetSelectedMenuItem()
{
string pageViewed = this.Page.AppRelativeVirtualPath;
foreach (MenuItem item in Menu.Items)
{
if (item.ChildItems.Count > 0)
{
if (pageViewed == item.Value)
{
item.Selected = true;
}
else
{
foreach (MenuItem childItem in item.ChildItems)
{
if (pageViewed == childItem.Value)
{
if (childItem.Parent != null)
{
childItem.Parent.Selected = true;
}
}
}
}
}
else
{
if (pageViewed == item.Value)
{
item.Selected = true;
}
}
}
}
Figured it out with help of related question:
Set item.selected in ASP.NET Menu Control
protected void Page_Load(object sender, EventArgs e)
{
MenuControl.MenuItemDataBound += new MenuEventHandler(MenuControl_MenuItemDataBound);
}
void MenuControl_MenuItemDataBound(object sender, MenuEventArgs e)
{
if (SiteMap.CurrentNode != null)
{
if (SiteMap.CurrentNode.ParentNode.Url == e.Item.NavigateUrl)
{
e.Item.Selected = true;
}
}
}