A lesson in adding Sharepoint navigation nodes

I learned something today while trying to add Top Navigation Bar navigation nodes in a SharePoint feature receiver. If you’re adding a node and also wanting to add child nodes of that node at the same time, make sure to actually add the parent node to the TopNavigationBar before trying to add the child nodes to the parent node.

In other words, this won’t work:

SPNavigationNode portalNode = new SPNavigationNode(“My Portal”, “/portal/Default.aspx”, false);

portalNode.Children.AddAsFirst(new SPNavigationNode(“Home”, “/portal/Home.aspx”, false));
portalNode.Children.AddAsLast(new SPNavigationNode(“Projects”, “/portal/Projects.aspx”, false));
portalNode.Children.AddAsLast(new SPNavigationNode(“HR/Benefits”, “/portal/HRBenefits.aspx”, false));
portalNode.Children.AddAsLast(new SPNavigationNode(“Management”, “/portal/Management.aspx”, false));

site.Navigation.TopNavigationBar.AddAsFirst(portalNode);

You have to do this:

SPNavigationNode portalNode = new SPNavigationNode(“My Portal”, “/portal/Default.aspx”, false);
site.Navigation.TopNavigationBar.AddAsFirst(portalNode);

portalNode.Children.AddAsFirst(new SPNavigationNode(“Home”, “/portal/Home.aspx”, false));
portalNode.Children.AddAsLast(new SPNavigationNode(“Projects”, “/portal/Projects.aspx”, false));
portalNode.Children.AddAsLast(new SPNavigationNode(“HR/Benefits”, “/portal/HRBenefits.aspx”, false));
portalNode.Children.AddAsLast(new SPNavigationNode(“Management”, “/portal/Management.aspx”, false));

If you do it the first way, the Navigation property of portalNode.Children will be null and it will cause an ArgumentNullException to be thrown. At least, I believe this was the cause of the problem. Adding the parent node (portalNode in my example) to the TopNavigationBar first causes portalNode.Children.Navigation to have a value and therefore no exception is thrown.

No comments yet.