unwanted treeview node duplicating at the end of list

44 views Asked by At

I have the following code but cant seem to find a reason (nor a solution) to why the parent node keeps appearing at the end of the list as a duplicate?

Imports System.IO
Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim di As New IO.DirectoryInfo("c:\la")
    Dim diar1 As IO.FileInfo() = di.GetFiles()
    Dim dra As IO.FileInfo

    For Each dra In diar1

        'Dim sr As StreamReader = New StreamReader(dra.FullName)
        If System.IO.Path.GetExtension(dra.Name).ToLower() = ".xls" Then
            TreeView1.Nodes.Add("Offerts")
            TreeView1.Nodes(0).Nodes.Add(dra.Name)
        End If
    Next

End Sub
End Class

1

There are 1 answers

1
Tony Hinkle On BEST ANSWER

On the first .xls file it finds, it creates an "Offerts" node in the root of the tree, and then creates a node with the filename under "Offerts".

On subsequent .xls files, it creates another "Offerts" node in the root, and then creates a node with the filename under the first node (the first "Offerts" node that was created).

So I think what you want to do is just create the "offerts" node once, at the root, so TreeView1.Nodes.Add("Offerts") should not be run each time it finds an .xls file. So replacing that line with something like:

If TreeView1.Nodes.Count = 0 Then TreeView1.Nodes.Add("Offerts")

Will work, given the scenario. If the treeview already has nodes, you'll have to modify that logic.