KeyszerS
KeyszerS

Reputation: 684

TreeView detect node select but not when checking or unchecking

I have an event that fires using the AfterSelect Event, and this works just fine, but I do not want this event to fire if the user either checks or unchecks the checkbox of this or any node in the tree. Alternatively, the event can fire, but then I need to know inside the event if it was fired as a result of a check or uncheck of the checkbox. I have tried using NodeMouseClick instead but I get the same unwanted result, and I have also tried removing the event handler using BeforeCheck and adding it back using AfterCheck, like so:

private void MyTree_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
    this.MyTree.AfterSelect -= new System.Windows.Forms.TreeViewEventHandler(this.MyTree_AfterSelect);
}

private void MyTree_AfterCheck(object sender, TreeViewEventArgs e)
{
    this.MyTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.MyTree_AfterSelect);
}

private void MyTree_AfterSelect(object sender, TreeViewEventArgs e)
{
    ShowMyInfo(e.Node);
}

but the AfterSelect event still fires.

I cannot rely on AfterCheck because then it won't fire if you simply select the node. I also cannot rely on checking if e.Node.Selected == true, because the node might already be checked, and I want the event to fire if the node is in fact deliberately selected.

Is there any event handler I can use that will trigger only if a node is SELECTED, and not CHECKED or UNCHECKED, or any way I can detect if a node that's just been selected has been checked or unchecked.

Using Visual Studio 2019 with a C# WinForms .NET Framework application.

Upvotes: 1

Views: 541

Answers (1)

KeyszerS
KeyszerS

Reputation: 684

As @Jimi and @dr.null have pointed out, I am using the right event after all. AfterSelect will not fire just because you checked or unchecked the checkbox.

The problem that I had was that I have code that will select a node if you right click it (right clicking does not automatically select a node).

Old Code:

    private void MyTree_MouseDown(object sender, MouseEventArgs e)
    {
        MyTree.SelectedNode = MyTree.GetNodeAt(e.X, e.Y);
    }

New Code:

    private void MyTree_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right) MyTree.SelectedNode = MyTree.GetNodeAt(e.X, e.Y);
    }

I was inadvertently firing off my own event because I did not check for which mouse button was clicked on the MouseDown event. Thank you for the help!

Upvotes: 1

Related Questions