For a couple of days, I was looking around for a way to expand a treeview menu to the node you are currently on. On a site with nodes that go several levels deep, it is a pain to have to open all the nodes every time a postback occurs.
I found code samples online and followed so many goosechases. Some people put a marker in the session to let them know where their node was. Others tried to do some clever javascript which didn’t seem to work for me. It seems to be some code that is heavily in demand.
Finally, I found a blog post by Walt Ritscher which helped me get what I wanted in a few lines of code. It doesn’t maintain the state of all open and closed nodes on the tree, but it does open the tree to the node with the URL of the page you are on. It took me so long to find his blog post from last year, that I thought I would add another link here:
http://waltritscher.com/blog/ramblings/archive/2006/05/18/843.aspx
His examples are in VB.Net, but a conversion to c# is not difficult. Here are my code examples:
In the .aspx page:
<asp:TreeView ID=”TreeView1″ ExpandDepth=”0″ OnTreeNodeDataBound=”treeMainMenu_TreeNodeDataBound” PopulateNodesFromClient=”false” NodeWrap=”false” HoverNodeStyle-ForeColor=”green” HoverNodeStyle-Font-Underline=”true” NodeIndent=”10″ Height=”100%” runat=”server” DataSourceID=”SiteMapDataSource1″>
</asp:TreeView>
Notice the “OnTreeNodeDataBound” and “PopulateNodesFromClient” attributes.
In the code behind:
protected void treeMainMenu_TreeNodeDataBound (
Object sender,
System.Web.UI.WebControls.TreeNodeEventArgs e )
{
if (Request.Url.PathAndQuery == e.Node.NavigateUrl) {
e.Node.ExpandAll();
}
if (e.Node.NavigateUrl == “”) {
e.Node.SelectAction = TreeNodeSelectAction.Expand;
}
}
Anyway, thanks to Walt for his blog post. I looked over some other posts in his blog and found it very interested. You might want to have a look too.
David Price says
I’ve been trying to work out a solution to this problem for hours… the key thing that was required (for me at least) is the PopulateNodesFromClient=”false” property…
Thanks so much 🙂