Hi,
I am using the following code to add all files and sub-directories to a Treeview control. The user can select a directory (using a folder browser dialog) and this code will add that directory, and all it's files and sub-directories, to the Treeview:
vb.net Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Using fbd As New FolderBrowserDialog If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then Dim n As New TreeNode(IO.Path.GetFileName(fbd.SelectedPath)) n.Tag = fbd.SelectedPath n.Name = fbd.SelectedPath TreeView1.Nodes.Add(n) PopulateTreeview(n) End If End Using End Sub Public Sub PopulateTreeview(ByVal node As TreeNode) 'Add directories Dim dirInfo As New IO.DirectoryInfo(node.Name) For Each d As IO.DirectoryInfo In dirInfo.GetDirectories Dim n As New TreeNode(d.Name) n.Tag = d.FullName n.Name = d.FullName 'Resursively add sub-directories PopulateTreeview(n) node.Nodes.Add(n) Next 'Add files For Each f As IO.FileInfo In dirInfo.GetFiles Dim n As New TreeNode(f.Name) n.Tag = f.FullName n.Name = f.FullName node.Nodes.Add(n) Next End Sub
I have noticed now that it is now extremely fast however. I would like the actual updating of the treeview to happen in a background thread so the UI doesn't lock up. But I've never done any threading so I need some help...
I have tried a few ways, mainly 'copying' the code from this recent codebank submission. However, I keep getting the obvious cross-thread call issue that I am adding nodes to the 'node' parameter, which is not allowed.
I am at a loss at how to do this otherwise. How can I update a Treeview like this if I have to recursively add nodes to the 'node' parameter, which is not 'available' in a separate thread?
Thanks!




Reply With Quote