Search code examples
vb.nettreeview

(VB.NET) Change images on TreeView


I have a tree view TreeView1 which works fine and 2 images in ImageList1 the first image (0) is a folder and the second image (1) is a file icon. I can't seem to get the icons to be folders for folders and files for files. They are always all folder icons or always file icons. Below is my code. Any ideas?

...
...
...
    '==================== LOAD FOLDERS FROM SELECTED DIRECTORY ====================
    Public Sub LoadDirectory(ByVal Dir As String)
        Dim di As DirectoryInfo = New DirectoryInfo(Dir)
        Dim Tree1 As TreeNode = TreeView1.Nodes.Add(di.Name)
        Tree1.Tag = di.FullName
        Tree1.StateImageIndex = 0
        LoadFiles(Dir, Tree1)
        LoadSubDirectories(Dir, Tree1)
    End Sub
    '==================== LOAD SUB-FOLDERS FROM SELECTED DIRECTORY ====================
    Private Sub LoadSubDirectories(ByVal dir As String, ByVal td As TreeNode)
        Dim subdirectoryEntries As String() = Directory.GetDirectories(dir)
        For Each subdirectory As String In subdirectoryEntries
            Dim di As DirectoryInfo = New DirectoryInfo(subdirectory)
            Dim Tree2 As TreeNode = td.Nodes.Add(di.Name)
            Tree2.StateImageIndex = 0
            Tree2.Tag = di.FullName
            LoadFiles(subdirectory, Tree2)
            LoadSubDirectories(subdirectory, Tree2)
        Next
    End Sub
    '==================== LOAD FILES FROM SELECTED DIRECTORY ====================
    Private Sub LoadFiles(ByVal dir As String, ByVal td As TreeNode)
        Dim Files As String() = Directory.GetFiles(dir, "*.*")

        For Each file As String In Files
            Dim fi As FileInfo = New FileInfo(file)
            Dim Tree3 As TreeNode = td.Nodes.Add(fi.Name)
            Tree3.Tag = fi.FullName
            Tree3.StateImageIndex = 1 '*** Not changing to Index 1 which is "File" Icon ***
        Next
    End Sub

When I run this code, all folders and files show the icon at index 0 which is a "folder" icon in the ImageList. The code I think is the issue is each of the Tree.StateImageIndex = 1 or Tree.StateImageIndex = 0 but maybe I am missing something? I want folders to be the image at index 0 and and files to be the image at index 1.


Solution

  • The problem is TreeView.StateImageIndex is incorrect and should be just TreeView.ImageIndex and then everything will work. In addition, one also needs TreeView.SelectedImageIndex set, otherwise when you click and highlight a node it'll change to the image at index 0.