View Single Post
  #1 (permalink)  
Old 06-27-2007, 08:48 AM
ccoonen ccoonen is offline
PT Staff
Awards Showcase
Quality Tutorial Quality Tutorial Quality Tutorial Quality Tutorial 
Total Awards: 4
Join Date: Jun 2007
Location: Wisconsin
Posts: 317
iTrader: (0)
ccoonen is on a distinguished roadccoonen is on a distinguished roadccoonen is on a distinguished roadccoonen is on a distinguished road
Icon11 VB.NET 2005 Daily Lesson [6.27.07] - Recursive TreeNode Creation

If you are ever working with a TreeView control, which is what Windows Explorer uses to explore Files and Folders, then you will realize that recursion is the only way to go. The TreeView control uses a TreeNode as a datasource and is n-level with infinite parent, children, nodes, leaves etc... Here is a function that will build your TreeNode recursively by taking a ParentNode as a treenode, adds a node, finds all children, adds all children, and repeat.

This is built off a Strongly Typed Dataset with an ID field that link to it's parent in the same field. For example, Fishing would have ID 5 and a ParentID of 0... Fishing would be a Root Item, but Fly Fishing would have a ParentID of 5 so it is a child of Fishing.

Code:
 Private Shared Function GetAllTreeNodes(ByRef CategoryItem As Category, ByRef ParentNode As TreeNode) As TreeNode
  Dim NewParentNode As New TreeNode
  If ParentNode.Text = "" Then
    NewParentNode = ParentNode.Nodes.Add("ROOT_LEVEL_NODE", " Categories")
    NewParentNode.Tag = -1
  Else
    NewParentNode = ParentNode.Nodes.Add(CategoryItem.CategoryID, CategoryItem.Name)
    NewParentNode.Tag = CategoryItem.CategoryID
  End If

  Using CategoryAdapter As New DAL.TableAdapters.CategoryTableAdapter()
    Using CategoryTable As DAL.CategoryDataTable = CategoryAdapter.GetByParentCategoryID(CategoryItem.CategoryID)
      For Each CategoryRow As DAL.CategoryRow In CategoryTable
        GetAllTreeNodes(ConstructObjFromDataRow(CategoryRow), NewParentNode)
      Next
    End Using
  End Using
  Return NewParentNode
End Function
Reply With Quote
The Following User Says Thank You to ccoonen For This Useful Post:
HelloWorld (06-27-2007)