Adding nodes to treeview using thread

  • Thread starter Thread starter Jared
  • Start date Start date
J

Jared

Hello,
I am trying to add nodes to a treeview from a separate thread, but, I
haven't had any luck. I have searched and read and ran the examples but I
haven't had much luck. What I want to do is traverse my AD structure adding
all of my OU's to a treeview control; the only problem is my structure is
quite large, and I don't want the perceived "lock" the user sees while it is
loading. Does anyone have a small example that adds nodes to a treeview
across threads? Thanks in advance.

This article provides some insight, but, I don't know how to use a delegate
that has arguments.
http://samples.gotdotnet.com/quickstart/howto/doc/WinForms/WinFormsThreadMar
shalling.aspx

Thanks in advance,
Jared
 
I have found the answer to my question, thanks to a post by Herfried Wagner
in a google groups search and to Nicholas Paldino. Here is the results. It
was much easier than I thought, I just didn't understand it at first.

'FORM 1 - contains a treeview and button

Dim Test As New TreeThread

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Test.Tree = Me.TreeView1
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim th As New Threading.Thread(AddressOf Test.Start)
th.Name = "testing"
th.Start()
End Sub

'CLASS TreeThread
Public Delegate Sub AddTreeViewNodeDelegate(ByVal Node As TreeNode)

Public Class TreeThread
Public Tree As TreeView

Public Sub Start()
For counter As Integer = 1 To 250
Dim NewNode As New TreeNode
With NewNode
.Text = "Node " & counter
End With
Tree.Invoke(New AddTreeViewNodeDelegate(AddressOf
AddTreeViewNode), New Object(0) {NewNode})
Next
End Sub

Public Sub AddTreeViewNode(ByVal Node As TreeNode)
'Add the node to the treeview
Me.Tree.Nodes.Add(Node)
End Sub
End Class

And that's it, super easy. Thanks again to Herfried and Nicholas!
 
Back
Top