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:
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.         Using fbd As New FolderBrowserDialog
  3.             If fbd.ShowDialog = Windows.Forms.DialogResult.OK Then
  4.  
  5.                 Dim n As New TreeNode(IO.Path.GetFileName(fbd.SelectedPath))
  6.                 n.Tag = fbd.SelectedPath
  7.                 n.Name = fbd.SelectedPath
  8.  
  9.                 TreeView1.Nodes.Add(n)
  10.                 PopulateTreeview(n)
  11.  
  12.             End If
  13.         End Using
  14.     End Sub
  15.  
  16.     Public Sub PopulateTreeview(ByVal node As TreeNode)
  17.        
  18.         'Add directories
  19.         Dim dirInfo As New IO.DirectoryInfo(node.Name)
  20.         For Each d As IO.DirectoryInfo In dirInfo.GetDirectories
  21.             Dim n As New TreeNode(d.Name)
  22.             n.Tag = d.FullName
  23.             n.Name = d.FullName
  24.  
  25.             'Resursively add sub-directories
  26.             PopulateTreeview(n)
  27.             node.Nodes.Add(n)
  28.         Next
  29.  
  30.         'Add files
  31.         For Each f As IO.FileInfo In dirInfo.GetFiles
  32.             Dim n As New TreeNode(f.Name)
  33.             n.Tag = f.FullName
  34.             n.Name = f.FullName
  35.  
  36.             node.Nodes.Add(n)
  37.         Next
  38.     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!