Question How would add nodes to a treeview from a tab indented file

keb1965

Well-known member
Joined
Feb 9, 2009
Messages
103
Programming Experience
10+
I have a file that is formatted (actually I have several files) with tab indents that represents a treeview. I need to import that file into a treeview so it appears like the file.

VB.NET:
Top Node1
        Child Node1_1
        Child Node1_2
                Child Node1_2_1
Top Node2
Top Node3
        Child Node3_1
        Child Node3_2
                Child Node3_2_1
                        Child Node3_2_1_1
                                Child Node3_2_1_1_1


I need it to look like the attached picture when imported.
 

Attachments

  • treeview.PNG
    treeview.PNG
    3.6 KB · Views: 39
VB.NET:
Private Sub Form1_Load(ByVal sender As Object, _
                       ByVal e As EventArgs) Handles MyBase.Load
    Dim parentNodes As TreeNodeCollection = Me.TreeView1.Nodes
    Dim previousNode As TreeNode = Nothing
    Dim currentNode As TreeNode = Nothing
    Dim level As Integer

    For Each line As String In IO.File.ReadAllLines("C:\Tree.txt")
        level = Me.GetLevel(line)
        currentNode = New TreeNode(line.Trim())

        If previousNode IsNot Nothing Then
            If level > previousNode.Level Then
                'This node is a child of the previous node.
                parentNodes = previousNode.Nodes
            ElseIf level < previousNode.Level Then
                'This node is a level higher than the previous node.
                Do
                    previousNode = previousNode.Parent
                Loop Until level = previousNode.Level

                If previousNode.Parent Is Nothing Then
                    parentNodes = TreeView1.Nodes
                Else
                    parentNodes = previousNode.Parent.Nodes
                End If
            End If
            'Else
            'This node is a sibling of the previous node.
        End If

        parentNodes.Add(currentNode)
        previousNode = currentNode
    Next
End Sub

Private Function GetLevel(ByVal line As String) As Integer
    Dim level As Integer = 0

    For Each ch As Char In line
        If ch = ControlChars.Tab Then
            level += 1
        Else
            Exit For
        End If
    Next

    Return level
End Function
 
Back
Top