ASP .NET Treeview Control, weird problem when you Programmatically expand the nodes.

Published on : May 23, 2007

Category : Microsoft Azure

Saravana

Author

One of my supporting project required building a web site using TreeView control to show hierarchical data. I used “NavigateUrl” property while data binding, so that every node in the tree view will have proper link something like http://abc.com/bts/default.aspx instead of Javascript:__doPostBack. Even though all of my pages are going to have the treeview control on the left, I’ll lose the expanded status because the control will be navigated to a brand new page and whole page will be loaded from scratch. So, my requirement is to set the treeview expanded status programmatically. What do you think of this line of code? TreeView1.FindNode(“BizTalk Server|Planning and Architecture|Patterns”).Expand(); (“|” is the path separator) Perfectly alright right? But, the output will only expand the node till “Planning and Architecture”, I tried different things like putting the code in different event handlers like page_prerender, treeview_databound, navigating to the node via Nodes and ChildNodes property etc, etc. Whatsoever I couldn’t make it work. Google search revealed similar problems but no solution. At last I managed to find the solution from the book “Professional ASP .NET 2.0” (Page: 525) the code should be written this way: TreeView1.FindNode(“BizTalk Server”).Expand(); TreeView1.FindNode(“BizTalk Server|Planning and Architecture”).Expand(); TreeView1.FindNode(“BizTalk Server|Planning and Architecture|Patterns”).Expand(); Extract from the book: “Note that you had to expand each of the nodes individually until you got to the “Planning and Architecture” node, If you simply used TreeView1.FindNode(“BizTalk Server|Planning and Architecture|Patterns”).Expand(); in the treeview1_DataBound method, the “Pattern” node would indeed be expanded, but the parent nodes above it (“Planning and Architecture” and “BizTalk Server”) would not have been expanded and you wouldn’t see the expanded “Patterns” node when invoking the page. (Try it; it’s interesting.)” What a weird programming style they have adapted for this? Is it not just common sense the control should expand all its parent node to show itself? The last sentence “Try it; it’s interesting” is actually present in the book. I was almost about to buy a commercial product, just thinking there is a huge bug in the ASP .NET 2.0 Treeview control. Nandri! Saravana