3
votes

I am using the Windows Forms TreeView control.

The way i have it hooked up is as followed (simplified):

TreeView treeView = new TreeView();

treeView.BeforeSelect += beforeSelect;

private void beforeSelect(sender, args)
{
     MessageBox.Show("Some msg");

     // more code
}

In certain scenarios, the call to MessageBox.Show triggers another raising of the BeforeSelect event, which triggers another, and another, ...

It seems this event is raised PER ITEM in the treeview (i have counted the number of times it is raised).

I have searched all over the internet on more information for why this could occur.

One thing i've found was that TreeView will automatically select the first node when gaining focus. This does not explain however why the event is fired as the number of treenode items in the tree.

Any help would be appreciated on this. I am considering raising a Microsoft Connect bug for this, as it seems like a very weird behavior that is not consistent with how i think the control should work.

3

3 Answers

3
votes

Would it be enough to simply block yourself like the following?

private bool _inside;

private void beforeSelect( object sender, EventArgs args )
{
    if ( !_inside )
    {
        _inside = true;

        MessageBox.Show("Some msg");

        // more code

        _inside = false;
    }
}

This would disallow "recursive" calls of your function.

3
votes

the BeforeSelect event isn't fired multiple times by default.

when you select a node, you show a dialog(here messagebox) which interrupts the selection event or task however and after you close the dialog the selection event fires again based on the interruption. You should use AfterSelect event of the treeview to do things... and BeforeSelect only for validation..

Please look at this code - run it

void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
    e.Node.Tag = (int)(e.Node.Tag ?? 0) + 1;
    int count = (int)(e.Node.Tag); 
    e.Node.Text = String.Format("selected {0} Count: {1}", e.Action.ToString(), count);
 }
-2
votes

When you define an object,you should write like this;

True Write:

private static TreeView projectagac; 
...
...
...
projectagac = new TreeView();

thus you will create only one object.