Pages

Wednesday, 30 May 2012

Populate Treeview Recursively

The following code snippet demonstrates how to populate a tree view control by making use of a very simple recursive method and an interface:

Firstly, the interface:

   /// <summary>  
   /// Structure Interface  
   /// </summary>  
   public interface IStructure  
   {  
     /// <summary>  
     /// Gets or sets the ID.  
     /// </summary>  
     /// <value>  
     /// The ID.  
     /// </value>  
     string ID { get; set; }  
     /// <summary>  
     /// Gets or sets the parent ID.  
     /// </summary>  
     /// <value>  
     /// The parent ID.  
     /// </value>  
     string ParentID { get; set; }  
     /// <summary>  
     /// Gets the display value.  
     /// </summary>  
     string DisplayValue { get; }  
   }  

Secondly, let's look at the method:

           /// <summary>  
           /// Binds the tree view.  
           /// </summary>  
           /// <param name="nodeCollection">The node collection.</param>  
           /// <param name="parentNode">The parent node.</param>  
           private void BindTreeview<T>(IEnumerable<T> nodeCollection, TreeNode parentNode)   
                where T : IStructure  
           {  
                var nodes = nodeCollection.Where(x => parentNode == null ? x.ParentID == null : x.ParentID == (((T)parentNode.Tag).ID));  
                foreach (var node in nodes)  
                {  
                     TreeNode newNode = new TreeNode();  
                     newNode.Text = node.DisplayValue;  
                     newNode.Tag = node;  
                     if (parentNode == null)  
                     {  
                          this.tViewProdStructure.Nodes.Add(newNode);  
                     }  
                     else  
                     {  
                          parentNode.Nodes.Add(newNode);  
                     }  
                     this.BindTreeview(nodeCollection, newNode);  
                }  
           }  

Okay, so that was a basic copy and paste job. To use the above code, we can do something like (obviously, this goes without saying, that the StructureResponse class that is used in the List<T> below, implements the IStructure interface):

      // get the structure based on the equipment ID and the serial number (from database)  
      List<StructureResponse> equipResultCollection = DataInterface.GetStructureFromDatabase(new StructureRequest(this.EquipmentID, this.SerialNumber));  
      try  
      {  
           // begin the update - this will suspend the UI  
           this.tViewProdStructure.BeginUpdate();  
           // build the tree view structure  
           this.BindTreeview(resultCollection, null);  
      }  
      finally  
      {  
           // resume UI responsiveness  
           this.tViewProdStructure.EndUpdate();  
      }  

And that's, that ...
Hope it helps!