Form.Controls collection management

  • Thread starter Thread starter Paolo
  • Start date Start date
P

Paolo

Hi all,
I have this kind of problem:
I have a windowsform with a treeview(tvwMain) filled by
nodes of different kind, derived from TreeNode; every
node has a method getPanel() that return a different
panel for every kind of node.
Everytime I select a node within the treeview the
following code is executed:

private void tvwMain_AfterSelect(object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
this.Controls.Remove(pnl);
TreeNode a = (TreeNode)e.Node;
pnl = a.getPanel();
this.Controls.Add(pnl);
}


Now, all work fine if these event occour slowly(normal
click selection works fine); instead, if, for example, I
move in the tree with the arrows keys the form's Controls
collection contains more than one pnl object, as
expected. So, the panel displayed in my form is not the
right one.
Does anybody knows how can I do to avoid this kind of
problem?

thank you
 
Paolo,

This looks like a threading problem - in that if all the calls to the event
procedure were serialised then the problem should not exist and only one
panel should be added at any time.

Hence, I would suggest using a lock to prevent multiple concurrent
invocations of the event procedure. E.g.

private void tvwMain_AfterSelect(object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
Panel oldPnl = pnl;
TreeNode a = (TreeNode)e.Node;
pnl = a.getPanel();
if (pnl != oldPnl)
{
lock(this)
{
this.Controls.Remove(oldPnl);
this.Controls.Add(pnl);
}
}
}

Hope this helps,

Neil.
 
Back
Top