Saturday, October 4, 2008

Programatically adding nodes to Top Navigation Control

Scenario:
You want to programatically add node to Top Navigation Control

Solution:
You can add child nodes to Site Collection's TopNavigationBar

Code:

using (SPWeb site = new SPSite("http://localhost")) {

SPNavigationNodeCollection topNav = site.Navigation.TopNavigationBar;

// create top navigation tab & add to top nav bar
SPNavigationNode topNavMenuItem = new SPNavigationNode("Site Collection Galleries", string.Empty, false);
topNav[0].Children.AddAsLast(topNavMenuItem);

// create first drop down pointing to Master Page Gallery
SPNavigationNode mpg = new SPNavigationNode("Master Page Gallery", string.Format("{0}/_catalogs/masterpage", site.Url), true);
topNavMenuItem.Children.AddAsFirst(mpg);

// create first drop down pointing to Web Part Gallery
SPNavigationNode wpg = new SPNavigationNode("Web Part Gallery", string.Format("{0}/_catalogs/wp", site.Url), true);
topNavMenuItem.Children.AddAsLast(wpg);

// create first drop down pointing to List Template Gallery
SPNavigationNode ltg = new SPNavigationNode("List Template Gallery", string.Format("{0}/_catalogs/lt", site.Url), true);
topNavMenuItem.Children.AddAsLast(ltg);

// create first drop down pointing to Site Template Gallery
SPNavigationNode stg = new SPNavigationNode("Site Template Gallery", string.Format("{0}/_catalogs/wt", site.Url), true);
topNavMenuItem.Children.AddAsLast(stg);

// commit the changes
site.Update();
}
Article:

2 comments:

Tudor May 18, 2011 at 5:42 AM  

Nice code, but it didn't do anything. I've read somewhere that I have to set the MaximumDynamicDisplayLevels from the master page