Ok, i have two problems with my little treeview experiment. The treeview is supposed to display the filsystem kinda like Windows Explorer.
I do not want to load all the subfolders as childnodes on start, rather i put a call in the AfterExpand event to minimize the load time.
Problem is that the childnodes get added again and again after each expand/collapse of the parents.
Second problem is i am changing the node icon on right-click to display a checked icon, which i later intend to use while determining
which folders the user has selected. Problem is the recursive routine does not seem to go all the way down through all childnodes,
seems to only go two levels down.
Does anyone have any suggestions for this?
Code:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
TreeView1.Sort()
Dim rootDir As String = "C:\"
Dim root As TreeNode = TreeView1.Nodes.Add(rootDir)
root.Tag = rootDir
PopulateTreeView(rootDir, TreeView1.Nodes(0))
End Sub
Private Sub PopulateTreeView(ByVal dir As String, ByVal parentNode As TreeNode)
Try
Dim folder As String = String.Empty
Dim folders() As String = IO.Directory.GetDirectories(dir)
If folders.Length <> 0 Then
Dim folderNode As TreeNode = Nothing
Dim folderName As String = String.Empty
For Each folder In folders
folderName = IO.Path.GetFileName(folder)
folderNode = parentNode.Nodes.Add(folderName)
folderNode.Tag = folder
Next
End If
Catch ex As UnauthorizedAccessException
End Try
End Sub
Private Sub TreeView1_AfterExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterExpand
Dim n As System.Windows.Forms.TreeNode
For Each n In e.Node.Nodes
PopulateTreeView(n.Tag, n)
Next
End Sub
Private Sub TreeView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TreeView1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
TreeView1.SelectedNode = TreeView1.GetNodeAt(e.X, e.Y)
If TreeView1.SelectedNode.ImageIndex = 0 Then
CheckChildren(TreeView1.SelectedNode, 1)
Else
CheckChildren(TreeView1.SelectedNode, 0)
End If
End If
End Sub
Sub CheckChildren(ByVal parentNode As TreeNode, ByVal image As Integer)
parentNode.ImageIndex = image
parentNode.SelectedImageIndex = image
If parentNode.Nodes.Count > 0 Then
For Each child As TreeNode In parentNode.Nodes
CheckChildren(child, image)
Next
End If
End Sub
Cheers!