Sunday, November 26, 2006

Asp.net Tree view control, very useful But.

Asp.net 2.0 ships with a whole new set of controls. Navigation controls are one of them. In navigation control we have three options

  1. Sitemap path
  2. Menu
  3. Tree View

TreeView

 

Recently I have worked in a project which is a demo project where I had the pleasure of using the asp.net 2.0 tree view control. Below I will be demonstrating a simple way to use the treeview and some things that we should know while we use tree view control of asp.net 2.0 in our projects.

 

Obviously tree view control has node property and nodes can be create dynamically and modify the node collection on runtime. But it’s for only level one node. For level two nodes node is created just the way it is, but need to add in the child node property. So in a sense tree view has node property and nodes have no recursive node property and to deal with child node, node has child node collection.

 

Constructor of Node class has several overloads. Actually 5 of them are there.

 

TreeNode tn = new TreeNode("Text");

TreeNode tn = new TreeNode("Text", _value);

 

Here we should always be careful about the value property. This value property must be distinct for each collection.

 

For example if we have a Tree Node consists of three Nodes and each and every done has value property as a same value. SelectedNodeChanged even returns always the first node of the collection.

 

TreeNode tn1 = new TreeNode("Node One",-1);

TreeNode tn2 = new TreeNode("Node Two",-1);

TreeNode tn3 = new TreeNode("Node Three",-1);

TreeView1.Nodes.Add(tn1);

TreeView1.Nodes.Add(tn2);

TreeView1.Nodes.Add(tn3);

 

In the web application if we select node three that is tn3 … in SelectedNodeChanged event we will have th1 as SelectedNode. I don’t know how this happened but surely it happened. But if we provide different value in the value field of the node constructor this was okay. Even if we don’t provide any value things work just fine.

 

Tree view has a wide range of configuration and style settings. Among these StaticItemStyle and StaticItemHoverStyle is most useful.

 

Well sometime we need to disable a node in our view. But TreeNode class do not have any enable or disable property, rather it has selection Action Property. We need to set the selection property value to none to make a node disabled.