Creating TreeNode from Pipe delimited List

abhinay86

Member
Joined
Aug 20, 2009
Messages
7
Programming Experience
Beginner
Hi Guys,

I was given a list which contains a set of pipe (i.e |) limited strings for example

AllItems.Add("Directory|AAL ELEC")
AllItems.Add("Services|Support Group")
AllItems.Add("Supply|G.E")
'AllItems.Add("Supply|G.W")
'AllItems.Add("Supply|AAL FP")
AllItems.Add("Supply|Emg Servc|Emr svr")
AllItems.Add("Supply|AALGlobal")

Now i need to place these in treeview like The "directory" node contains "AAL Elec,"
The supply node contains "GE, GW, AAL FP, EMG Servc, AAL Global"
And the "Emg Servc" in "supply" contains "emr svr"
And so on..


VB.NET:
 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim AllItems As New List(Of String)()

        ' Add an item to the Collection
        AllItems.Add("Directory|PPL ELEC")
        AllItems.Add("Services|Support Group")
        AllItems.Add("Supply|G.E")
        AllItems.Add("Supply|G.W")
        AllItems.Add("Supply|PPL FP")
        AllItems.Add("Supply|Emg Servc|Serv")
        AllItems.Add("Supply|Emg Servc|Serv|Raj")
        AllItems.Add("Supply|PPL Global")   
 
        
        Try
            Dim N As New TreeNode()
            

            With Me.TreeView1.Nodes
                
                Dim duplicate As String = Nothing

                For Each s As String In AllItems()
                    If s.Contains("|") Then
                        Dim abhi As String() = s.Split("|")
                        If duplicate <> abhi(0) Then
                            N = .Add(abhi(0).ToString)
                        End If
                        For b As Integer = 1 To abhi.Length - 1
                            
                            N.Nodes.Add(abhi(b).ToString)



                            duplicate = abhi(0)

                        Next

                    End If

                Next

               
            End With


           

        Catch ex As Exception
            MsgBox("Error Loading Treeview." + ex.Message)
        End Try
        
    End Sub

But my code is limited for 2 nodes.
Can anyone help me to make it for unlimited coz the list changes frequently?

Thanks in advance
 
Last edited:
VB.NET:
For Each item As String In AllItems        
    Dim nodes As TreeNodeCollection = Me.TreeView1.Nodes
    For Each part As String In item.Split("|"c)
        If nodes.ContainsKey(part) Then
            'go to next level
            nodes = nodes(part).Nodes
        Else
            'add node and go to next level
            nodes = nodes.Add(part, part).Nodes
        End If
    Next
Next
 
Back
Top