The easiest way to do this is to write a recursive method. The way it operates will depend on whether you want to have the method return the entire tree-structured list, or output the data as it reads it. If you want to output the data as you read it, your code might look something like this:
Private Sub OutputTree(data As DataTable, parentId As String, indentationLevel As Integer)
For Each row As DataRow In GetChildRows(parentId)
OutputRow(row, indentationLevel)
OutputTree(data, row("ID").ToString(), indentationLevel + 1)
Next
End Sub
The above code assumes that you also implement a method called GetChildRows
which returns a list of all the rows that contain the given parent ID. It also assumes that you have a method called OutputRow
which outputs the given row at the given indentation level.
Then, you could call the method like this:
OutputTree(myDataTable, nothing, 0)
If you want to build and return a tree structure, which is arguably the better approach, your code might look something like this:
Private Function BuildTreeNodes(data As DataTable, parentId As String) As List(Of MyTreeNode)
Dim nodes As List(OfNew MyTreeNode)()
For Each row As DataRow In GetChildRows(parentId)
Dim node As New TreeNode()
node.Row = row
node.Children = BuildTreeNodes(data, row("ID").ToString())
nodes.Add(node)
Next
Return node
End Sub
The above code assumes that you have defined a MyTreeNode
class which would look something like this:
Public Class MyTreeNode
Public Property Row As DataRow
Public Property Children As List(Of MyTreeNode)
End Class
Then you could call the method like this:
Dim rootLevelNodes As List(Of MyTreeNode) = BuildTreeNodes(myDataTable, Nothing)