The TreeView control in ASP.NET 2.0 is one of my favourite controls for building easy-to-use navigation. But it has some limitations, or at least they appear to me as limitiations. The problem is to maintain the state of the nodes when jumping around pages, especially in an masterpage based UI.
So this is the task. I am using the Treeview to present product categories in hierarchy with an unlimited amount of childnodes. I am not interested in using the postback method with javascript as it will not be search-engine friendly. So what I need to do is to find some way to use NavigationUrl and still maintain the state of the tree without using viewstate or javascript.
To begin with I pass the ValuePath as a querystring for NavigateUrl of each Node.
Protected
Sub MyTree_TreeNodeDataBound(ByVal sender As
Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles MyTree.TreeNodeDataBound
e.Node.NavigateUrl &= "&path=" & e.Node.ValuePath
End
Sub
This will make my URLS look something like: /showcategory.aspx?category=123&path=Computers|Laptops|Accessories
Secondly, in the Page_Load event I must parse my Path parameter and expand each node:
Private
Sub ExpandTreenodeItem(ByVal path As
String)
If
Not path = String.Empty Then
Dim strPath() As
String = path.Split("|")
Dim strBuildPath As
String
Dim n As TreeNode
For
Each leaf As
String
In strPath
If strBuildPath = String.Empty Then strBuildPath = leaf Else strBuildPath &= "|" & leaf
n = MyTree.FindNode(strBuildPath)
If
Not n Is
Nothing
Then n.Expand()
n = Nothing
Next
End
If
End
Sub
Protected
Sub MyTree_DataBound(ByVal sender As
Object, ByVal e As System.EventArgs) Handles MyTree.DataBound
If
Not Request.QueryString("path") = ""
Then
ExpandTreenodeItem(Request.QueryString("path"))
End
If
End
Sub
The trick is to make the Path shorter and shorter and move all the way up to the root and expand at each level (first expand Computers, then expand Computers|Laptops and last expand Computers|Laptops|Accessories.
One might also consider expanding nodes with the Path parameter coming from another source, perhaps from a product view page where you have the categorization stored within the product object.