ipona

What in heavens name am I doing?

TreeView as Menu and highlight

| 0 comments

In a follow up to my tab-style menus post along comes a similar query about highlighting the parent path when using a TreeView control as your menu. The TreeView has a similar event to the Menu allowing you to check each node as it’s bound with data. So with a UI like:

<asp:SiteMapDataSource ID="menuData" runat="server" />
<asp:TreeView ID="tv1" runat="server" 
    DataSourceID="menuData"
    ontreenodedatabound="tv1_TreeNodeDataBound" />

You can have the following event code:

protected void tv1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
    SiteMapNode node = e.Node.DataItem as SiteMapNode;

    if (SiteMap.CurrentNode.IsDescendantOf(node))
    {
        e.Node.Text = String.Format("<span class='parentselected'>{0}</span>", e.Node.Text);
    }

    if (node.Url == SiteMap.CurrentNode.Url)
    {
        e.Node.Text = String.Format("<span class='selected'>{0}</span>", e.Node.Text);
    }
}

Add in the appropriate styles and now not only is the current item highlighted, but the path back to the parent is highlighted too.

Leave a Reply

Required fields are marked *.