Introduction
This article describes how to create a server-side treeview with JavaScript to prevent postbacks.
Background
I wanted to use a treeview control to group my data together, and didn't want a large number of postbacks on expand-collapse. I did an original version of this in ASP, and converted most of it over.
Using the Code
To use the dynamic treeview, simply place the control on the form and load the variables.
Once you have put the control on the form, you'll want to create a list of TreeNodeInfo
items as found in the DynamicTreeView
class file. The TreeNodeInfo
constructors will give you the ability to: add a node name, add sub nodes, add an object to be tied to the node, and gray out the selection for active/inactive.
Initialization
Drag DynamicTreeView
onto your ASPX page. In the Load or LoadComplete
events of your page, place your initialization of the tree nodes.
Dim lstTNI as New List(of TreeNodeInfo)()
Dim lstSubNodes as New List(of TreeNodeInfo)()
lstSubNodes.Add(New TreeNodeInfo("Sub Node 1"))
lstTNI.Add(New TreeNodeInfo("Node1", lstSubNodes.ToArray()))
Now that your tree node info lists are prepared, you are ready to add them to the dynamic treeview control.
Me.DynamicTreeView1.AddNodeRange(lstTNI.ToArray())
Each node has a JavaScript double click tied to it. For my particular project, I needed only the main nodes to have a double click event, so I created the ItemDoubleClicked(Item)
method.
var dblClick;
function ItemDoubleClicked(Item)
{
if (dblClick != null)
dblClick(Item);
}
This uses the style of the event handler found in C# where it is simply an object being called. If you wish to implement the double click event, you can create another bit of JavaScript that will look like:
function init()
{
dblClick = DoubleClickHandler;
}
function DoubleClickHandler(item)
{
}
Points of Interest
Feel free to play around with the HTML formatting, I'm not great at it, but the control does what I need it to, so I have no interest in toying with my server-side code until I finally figure it out.
When I created this, my original idea was to add all the nodes one at a time as they came in from the database. For this, I added the AddNode
method. Since looping through this would cause a serious performance hit because of the way I rebuilt the control on every add, I don't recommend this method unless you're working inside a page and adding things slowly (user adding).
Since ASP.NET has the incredibly nice feature of renaming all your controls dynamically and my JavaScript isn't all that hot, I had to include a prefix at the beginning of most of my dynamic control changes.
Afterthoughts
After doing more work in ASP.NET AJAX, I learned that this control can be duplicated quite easily in AJAX. However, if you're not able to use AJAX in your page, this is a decent solution, and can be ported to ASP fairly easily.