How To: Add a link to the Top Navigation Bar of a Site

Posted Wednesday, January 23, 2008 1:22 PM by C-Dog's .NET Tip of the Day

This begins the first in my series of posts on how to do stupid simple things in SharePoint. I find that some things in SharePoint are really pretty easy but there is not much out there on Google. Some this content may be new, some may be repeated, and some of this may already be buried in the SDK documentation somewhere. Anyhow, my goal is to contribute as much information as I can to help out new SharePoint developers.

Today's topic is how to add a link to the Top Navigation bar of a site in SharePoint. Typical places to do this is in a Feature Receiver where you are adding new pages. Assuming you already have a reference to the current site through a SPWeb object named currentSite, here is how to do it. Create a New SPNavigationNode object with the title you want in the link and a URL. Typically, you would just specify a relative URL (i.e.: MyCustomPage.aspx). Before adding the node, be sure that the page is created. If you don't, it will throw an exception.

SPNavigationNode navigationNode = new SPNavigationNode("My Page Title", "MyPage.aspx");

currentSite.Navigation.TopNavigationBar.AddAsLast(navigationNode);

In this case I am using AddAsLast which puts it at the end, there are also methods to Add after a specific node or at the beginning.

Removing a node is just as easy, but there are some limitations. I would have expected the TopNavigationBar object's Delete method to accept a title or url, but it does not. It requires either deleting by index or a reference to a SPNavigationNode object. So what you do is very similar to adding.

SPNavigationNode navigationNode = new SPNavigationNode("My Page Title", "MyPage.aspx");

currentSite.Navigation.TopNavigationBar.Delete(navigationNode);

I'll be posting more random things like this over the next few weeks.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=404

Filed under: ,