Question

I make windows form application. I have on form TreeView, I add few nodes and add ContextMenuStrip.

  var menu = new ContextMenuStrip();
  menu.Items.Add("Some text", new Bitmap(1, 1), new EventHandler(function_name));

  var treeView = new TreeView(..);
  treeView.ContextMenuStrip = menu;      

  treeView.Nodes.Add(new TreeNode()
  {
         ...
         Tag = someObject
  });

My problems is how can I check in function function_name on which treeNode was clicked and chosen option from ContextMenuStrip

edit

function_name sygnature

 public void pokaz_DoubleClick(object sender, EventArgs e)
 {
 }
Was it helpful?

Solution

You can handle the TreeNodeMouseClick event. In your TreeNodeMouseClickEventHandler you will have access to a TreeNodeMouseClickEventArgs argument. This argument contains a number of properties you can use to check which mouse button was clicked on which node. For example.

private TreeNode rightClickeNode;

void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        rightClickedNode = e.Node;
    }
}

You can then access rightClickedNode from your function_name.

OTHER TIPS

what is the signature of the function_name method?

generally you can check the content of the sender parameter but it could happen it is the TreeView and not the TreeNode, if so you can check the properties of the e parameter.

Another way is that at every mouse down you make sure you select the node under the mouse in the TreeView so when function_name executes you get your node taking treeview.SelectedNode

You can make the node selected right before the Context Menu is shown and then you just need to check the SelectedNode property. Something like this:

private void treeView_MouseDown(object sender, MouseEventArgs e)
{
    //See what node is at the location that was just clicked
    var clickedNode = treeView.GetNodeAt(e.Location);

    //Make that node the selected node
    treeView.SelectedNode = clickedNode;
}

private void function_name(object sender, EventArgs e)
{
    var currentNode = treeView.SelectedNode;

    //Do something with currentNode
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top