Populating TreeViews with data acquired from void static callback methods
-
Hi, I'm trying to populate a TreeView with info I'm gathering via a PeekCompleted callback for a MessageQueue. My PeekCompleted method, which is "void static", does not have any trouble populating a ListBox but the compiler complains that I must use Control.Invoke() from the callback to use TreeNode.Add(). Here are my questions: 1) Why? 2) Should I use Control.Invoke() or do this another way? All I'm trying to do is build a TreeView using data I collected from a callback method. What are my other options? TIA, Matt
-
Hi, I'm trying to populate a TreeView with info I'm gathering via a PeekCompleted callback for a MessageQueue. My PeekCompleted method, which is "void static", does not have any trouble populating a ListBox but the compiler complains that I must use Control.Invoke() from the callback to use TreeNode.Add(). Here are my questions: 1) Why? 2) Should I use Control.Invoke() or do this another way? All I'm trying to do is build a TreeView using data I collected from a callback method. What are my other options? TIA, Matt
Yes you should use
Control.Invoke
. This invokes the call on the thread on which the control was created, which is important. You should do this for yourListView
as well. Modifying the control from a different thread causes problems in the message queue. The technical details get down into what is encapsulated by the .NET Framework (much of it, anyway): Win32 APIs. To useInvoke
, take a look at this sample code to safely add aTreeNode
in the property thread:internal void SafeAdd(TreeNodeCollection nodes, TreeNode node)
{
if (nodes == null || node == null)
throw new ArgumentNullException(nodes == null ? "nodes" : "node");
if (treeView1.InvokeRequired)
{
Delegate d = new AddTreeNodeHandler(nodes.Add);
treeView1.Invoke(d, new object[] {node});
}
else nodes.Add(node);
}
private delegate int AddTreeNodeHandler(TreeNode node);Microsoft MVP, Visual C# My Articles