Assigning ToolStripMenu to many TreeView nodes and know which node was pressed on

51 Views Asked by At

I've TreeView object which i need to enable users to delete nodes from it, So i have delete ToolStripMenu that i assign to nodes enabled to be deleted. But i want to know which node was pressed on and fired the delete_toolStripMenuItem_Click event without using the treeView.SelectedNode property.

Is there a way to know the exact node that was pressed on ?

1

There are 1 best solutions below

0
On

Here's one approach. You handle the MouseDown() event of the TreeView and determine which TreeNode was Right Clicked with TreeView.GetNodeAt(). Store that TreeNode at Form level so you can access it in the Delete menu handler:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private TreeNode _TN = null;

    private void treeView1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            _TN = treeView1.GetNodeAt(e.X, e.Y);
        }
    }

    private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (_TN != null)
        {
            MessageBox.Show(_TN.Text);
        }
    }

}