Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLoad a TreeView from a text file with tabs denoting indentation in VB .NET
DescriptionThis example shows how to load a TreeView from a text file with tabs denoting indentation in Visual Basic .NET.
KeywordsTreeView, text file, load
CategoriesControls, Files and Directories, VB.NET
 
Read the file and count the leading tabs. Give the new node the right parent for its level of indentation.
 
' Load a TreeView control from a file that uses tabs
' to show indentation.
Private Sub LoadTreeViewFromFile(ByVal file_name As String, _
    ByVal trv As TreeView)
    ' Get the file's contents.
    Dim stream_reader As New StreamReader(file_name)
    Dim file_contents As String = stream_reader.ReadToEnd()
    stream_reader.Close()

    ' Remove line feeds.
    file_contents = file_contents.Replace(vbLf, "")

    ' Break the file into lines.
    Const charCR As Char = CChar(vbCr)
    Const charTab As Char = CChar(vbTab)
    Dim lines() As String = file_contents.Split(charCR)

    ' Process the lines.
    Dim text_line As String
    Dim level As Integer
    Dim tree_nodes() As TreeNode
    Dim num_nodes As Integer = 0
    ReDim tree_nodes(num_nodes)

    trv.Nodes.Clear()
    For i As Integer = 0 To lines.GetUpperBound(0)
        text_line = lines(i)
        If text_line.Trim().Length > 0 Then
            ' See how many tabs are at the start of the
            ' line.
            level = text_line.Length - _
                text_line.TrimStart(charTab).Length

            ' Make room for the new node.
            If level > num_nodes Then
                num_nodes = level
                ReDim Preserve tree_nodes(num_nodes)
            End If

            ' Add the new node.
            If level = 0 Then
                tree_nodes(level) = _
                    trv.Nodes.Add(text_line.Trim())
            Else
                tree_nodes(level) = tree_nodes(level - _
                    1).Nodes.Add(text_line.Trim())
            End If
            tree_nodes(level).EnsureVisible()
        End If
    Next i

    If trv.Nodes.Count > 0 Then trv.Nodes(0).EnsureVisible()
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated