How to set the array of paths on TreeView With 'Linq'

Mansour_Dalir 2,036 Reputation points
2023-07-24T04:22:05.3333333+00:00

hi

this My Array

dim MyArray as string()={"D:\Folder1\File1.pdf","D:\Folder1\File2.pdf","D:\Folder2"}

tre

Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2023-07-24T05:54:47.03+00:00

    Hi @Mansour_Dalir ,

    Please check if the following code helps.

        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    
            Dim MyArray As String() = {"D:\Folder1\File1.pdf", "D:\Folder1\File2.pdf", "D:\Folder2"}
    
            For Each path As String In MyArray
                AddPathToTreeView(path, TreeView1.Nodes)
            Next
        End Sub
    
        Private Sub AddPathToTreeView(path As String, nodes As TreeNodeCollection)
            Dim pathSegments As String() = path.Split("\"c)
            Dim currentNode As TreeNodeCollection = nodes
    
            For Each segment As String In pathSegments
                Dim existingNode As TreeNode = currentNode.Cast(Of TreeNode)().FirstOrDefault(Function(node) node.Text = segment)
    
                If existingNode Is Nothing Then
                    Dim newNode As TreeNode = New TreeNode(segment)
                    currentNode.Add(newNode)
                    currentNode = newNode.Nodes
                Else
                    currentNode = existingNode.Nodes
                End If
            Next
        End Sub
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.