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)
{
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With