3

I have a treeview in windows form. When I Left click a node in the treeview e.Node is showing correct value but when I right click the same node, e.Node is showing parent node value in the trreview Afterselect event. What could be the reason and how can I get the actual node even at Right click?

 private void trView_AfterSelect(object sender, TreeViewEventArgs e)
 {    
     //e.Node is parent Node at Right click
     //e.Node is correct node at Left Click
        if (e.Node.IsSelected)
        {


        }
 }
Anil kumar
  • 525
  • 2
  • 10
  • 32
  • 2
    [Right click select on .Net TreeNode](http://stackoverflow.com/questions/4784258/right-click-select-on-net-treenode) – Reza Aghaei Sep 09 '16 at 22:53

1 Answers1

2

The linked Post shows you how to select node using MouseDown.But you should know the MouseDown event triggers also when you click on +/- in TreeView while you want let the +/- perform it's original operation. So usually you need to check some other criteria to prevent unwanted behavior in TreeView:

  • You can check if the mouse down is not over a +/- by checking the result of HitTest method of TreeView.

  • You can check if the mouse down event is triggered by right mouse button by checking Button property of event args.

Example

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    TreeNode node = null;
    node = treeView1.GetNodeAt(e.X, e.Y);
    var hti = treeView1.HitTest(e.Location);

    if (e.Button != MouseButtons.Right ||
        hti.Location == TreeViewHitTestLocations.PlusMinus ||
        node == null)
    {
        return;
    }
    treeView1.SelectedNode = node;
    contextMenuStrip1.Show(treeView1, node.Bounds.Left, node.Bounds.Bottom);
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398