How to use Control.Invoke from a new thread

C

Christopher DuBuc

I am new to threading and am a little confused...

I have a windows form with which I have placed a user
control made up of a treeview control and some loading
methods. Since the loading of the treeview takes a while
(15 sec), I am attempting to run the treeview loading
logic in another thread.

I can start up a new thread and run my user-control's
method (below), but when that method attempts to add a
node to the treeview control, I get the following run-time
error:

Public Sub LoadTargetingForRegions()

'''''Company
Dim dt As DataTable = LoadCompany()

Dim dr As DataRow
For Each dr In dt.Rows

Dim nodeCompany As New TreeNode
nodeCompany.Tag = dr("COMPANYID")
nodeCompany.Text = dr("NAME")
trvTargeting.Nodes.Add(nodeCompany) '<=error
.........

"The action being performed on this control is being
called from the wrong thread. You must marshal to the
correct thread using Control.Invoke or Control.BeginInvoke
to perform this action."

My question is how do I use the Invoke method to
manipulate (add nodes to) my treeview control? I am
slightly familiar with using delegates, but I can't seem
to figure out how this method is supposed to work. Or is
there a different/better way I should be doing this?

Thanks in advance for any guidance that can be given,

Chris
 
H

Herfried K. Wagner [MVP]

Hello,

Christopher DuBuc said:
My question is how do I use the Invoke method to
manipulate (add nodes to) my treeview control? I am
slightly familiar with using delegates, but I can't seem
to figure out how this method is supposed to work. Or is
there a different/better way I should be doing this?

http://www.devx.com/dotnet/Article/11358

HTH,
Herfried K. Wagner
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top