Reputation: 5098
I have a TreeView where all nodes are assigned the same ContextMenuStrip.
When I right-click a TreeNode other than the one already selected and then select an item in the ContextMenuStrip, treeView1.SelectedNode is for the node that was selected before right clicking and not for the item that was right clicked.
How do I change this behavior so that it will correctly select the right clicked node before showing the ContextMenuStrip?
private void newGroupToolStripMenuItem_Click(object sender, EventArgs e)
{
TextFieldDialog t = new TextFieldDialog("New Order Group", "Enter the name of the new group");
t.ShowDialog();
if (t.DialogResult == DialogResult.OK)
{
int lastid = db.NewOrderGroup(t.Value, (int)treeView1.SelectedNode.Tag);
TreeNode node = new TreeNode(t.Value);
node.Tag = lastid;
treeView1.SelectedNode.Nodes.Add(node);
}
}
In the above code (int)treeView1.SelectedNode.Tag
returns the tag of the Node that was selected before I right clicked, and not the Node that was right clicked.
Upvotes: 3
Views: 1463
Reputation: 941545
It is a quirk of TreeView, only the left mouse button selects a node. Reset the ContextMenuStrip property and note the behavior, when you right-click the highlight does jump to the clicked node but it jumps right back after you release the button.
Fix it by implementing an event handler for the NodeMouseClick event. Select the node and show the context menu, like this:
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
if (e.Button == MouseButtons.Right) {
treeView1.SelectedNode = e.Node;
contextMenuStrip1.Show(treeView1, e.Location);
}
}
Upvotes: 9