views:

508

answers:

2

I added a context menu (add, cancel) to tree view dynamically. Now I want to show the selected tree node value when I click on context menu item click.

How can I do that?

+1  A: 

I assume you just need to know the text of the treenode? This code should do the job

string treeNodeText = this.treeView1.SelectedNode.Text;
MathiasJ
+1  A: 

I assume you want to know which node was right-clicked when the context menu is opened?

To determine this you can handle the mousedown event on the treeview and ensure the node you right-clicked is selected before the context menu is displayed.

    private void treeView1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var node = treeView1.HitTest(e.X, e.Y).Node;
            treeView1.SelectedNode = node;
        }
    }

In the ToolStripMenuItem's click handler you can check treeView1.SelectedNode, it will be null if the user right clicked the treeview outside a node.

    private void addToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (treeView1.SelectedNode != null) MessageBox.Show("Node selected: " + treeView1.SelectedNode.Text);
    }
Dag