Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tabbed text into treeview

In VB.NET, how can I convert a multi-line string in this format...

Area 52
   Sector 19
      Stage 7
      Library 15
   Sector 32
      Link 30
      Portal 20`

...(each indent is a vbTab), into a treeview control like the following:

image of treeview example

I think that a recursive function would work properly, but I don't know how to create one that works correctly yet.

like image 883
Adam Avatar asked Jul 29 '26 14:07

Adam


1 Answers

first, you need to parse your string. Create an object that will store your data. In pseudo-code:

class Node
    Text as string
    Level as Integer
end class

Now, you need to fill list of these nodes

dim lines() as string = myString.split(Environment.NewLine)

Iterate and investigate lines

Dim nodeList as new List(Of Node)()
for each line as string in lines
    dim lenBefore as integer = line.Length
    dim lenAfter as integer = line.Trim().Length
    dim n as new Node()
    n.Text = line.Trim()
    n.Level = (lenBefore - lenAfter) / numberOfEmptySpacesInIndent 'for example indent 4 spaces
next

Now, you have the list and you need to turn it into Treeview

dim previousTreeNode as TreeNode
dim previousNode as Node

for each n as Node In nodeList
    ' here create new tree node using n.Text       
    dim newTreeNode = .....

    if n.Level = 0 then 
        tv.Nodes.Add(newTreeNode)
    else if n.Level = previousNode.Level Then
        previousTreeNode.Parent.Nodes.Add(newTreeNode)
    else if n.Level > previousNode.Level Then
        previousTreeNode.Nodes.Add(newTreeNode)
    else if n.Level < previousNode.Level Then
        previousTreeNode.Parent.Parent.Nodes.Add(newTreeNode)
    end if

    previousNode = n
    previousTreeNode = newTreeNode

next

This should do it. Although, this is pseudo-code and I haven't tested anything. If you want recursion, you need to establish relationship between lines. this code is based on indent and there is no relationship. I guess, it is possible, once you've obtained the level based on indent, you could traverse the list of nodes to find the parent and add properties. Yea, if you create that object structure, it is easy then to copy it into tree nodes. But it is double work then.

like image 91
T.S. Avatar answered Aug 01 '26 03:08

T.S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!