views:

455

answers:

1

I have a simple Sitemap like this from asp:SiteMapDataSource:

Page 1 > Page 2 > Page 3

I would like to create foreach loop in C# that generates it instead for using asp:SiteMapPath because I need to add some exceptions to it. Now I cannot figure out how do I loop backwards from SiteMap.CurrentNode to SiteMap.RootNode?

+3  A: 

The property you are looking for is SiteMapNode.ParentNode

SiteMapNode currentNode = SiteMap.CurrentNode;
SiteMapNode rootNode = SiteMap.RootNode;
Stack<SiteMapNode> nodeStack = new Stack<SiteMapNode>();

while (currentNode != rootNode)
{
    nodeStack.Push(currentNode);

    currentNode = currentNode.ParentNode;
}

// If you want to include RootNode in your list
nodeStack.Push(rootNode);

SiteMapNode[] breadCrumbs = nodeStack.ToArray();
Richard Szalay
Thanks almost working. But how do I reverse this loop as the output starts from current node and not from root?
jpkeisala
Use a Stack<SiteMapNode>, and Push() each node onto the Stack. Stack<>.ToArray() will then return an array in the order you are looking for.
Richard Szalay
I've updated the example to include the Stack
Richard Szalay
Btw, if this has answered your question you can click on the tick mark on the left to prevent the question appearing in the "unanswered questions" area of the site.
Richard Szalay
Thank you very much!
jpkeisala