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