Wintellect Blogs

Hiding the Root Node from SiteMapPath

22 Jun , 2006  

ASP.NET developers often set SiteMapDataSource’s ShowStartingNode property to false to hide the root node from TreeView and Menu controls. Unfortunately, that doesn’t hide the root node from SiteMapPath controls, because SiteMapPaths bypass SiteMapDataSources and go directly to the site map provider. I’m working on a project right now that requires me to hide the root node from SiteMapPath controls. Here’s how I accomplished it.

Place the following code in Global.asax:

void Application_Start(object sender, EventArgs e) 
{
    //
    // Register a handler for SiteMap.SiteMapResolve events to hide the
    // root node from SiteMapPath controls.
    //
    SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(HideRootNode);
}

static SiteMapNode HideRootNode(Object sender, SiteMapResolveEventArgs e)
{
    //
    // Hide the root node from SiteMapPath controls by cloning the site
    // map from the current node up to the node below the root node and
    // setting that node’s ParentNode property to null.
    //
    SiteMapNode node = SiteMap.CurrentNode.Clone();
    SiteMapNode current = node;
    SiteMapNode root = SiteMap.RootNode;

    if (current != root) // Just in case the current node *is* the root node!
    {
        while (node.ParentNode != root)
        {
            node.ParentNode = node.ParentNode.Clone();
            node = node.ParentNode;
        }
        node.ParentNode = null;
    }
    return current;
}
 

This code registers a handler for SiteMap.SiteMapResolve events, which fire each time a SiteMapPath requests the current node (SiteMap.CurrentNode). The handler creates a copy of the site map nodes from the current node up to the node directly underneath the root, and then hides the root node by making the node at the top of the chain the new root node.

On a slightly different subject, I’ve thoroughly enjoyed the World Cup matches, despite the U.S.’s dismal performance. I absolutely LOVE watching soccer–er, football–in Europe and wish I could see more of it. But have you noticed that every time a soccer player gets touched or tripped, he falls to the ground grimacing and writhing in pain? Most of these antics, I’m convinced, are for the benefit of the refs. Still, I wish soccer players would act more like men and less like wimps. The sport would be better for it!