3

I have a TreeView control with a bunch of TreeNodes. Each nodes ContextMenu has different MenuItems based on its state. So I am currently attaching each TreeNode its own ContextMenu.

TreeView tv = new TreeView();
TreeNode tn = New TreeNode();
tn.ContextMenu = GetContextMenu(state);
tv.Nodes.Add(tn);

Then in the click event for the MenuItem I try to get the TreeNode that the ContextMenu belonged to.

MenuItem mi = (MenuItem)sender;
ContextMenu tm = mi.GetContextMenu();
var sc = tm.SourceControl;

The problem is that tm.SourceControl == null. I noticed that TreeNode doesn't derive from Control. Is that why the SourceControl property is null? How can I get the appropriate TreeNode object? Or even the TreeView object?

scott
  • 2,991
  • 5
  • 36
  • 47
  • Can you look at this StackOverFlow prior post and see if it helps http://stackoverflow.com/questions/2527/c-sharp-treeview-context-menus – MethodMan Dec 16 '11 at 14:20
  • That helped. I didn't see that in my search. Thanks. What do I do with this question? – scott Dec 16 '11 at 14:25

1 Answers1

3

I'm not sure to understand your question.

When you have a click on the TreeView, you can do this to get the selected Node and :

void tvMouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        // Select the clicked node
        tv.SelectedNode = tv.GetNodeAt(e.X, e.Y);

        if(tv.SelectedNode != null)
        {
            myContextMenuStrip.Show(tv, e.Location)
        }
    }
}
LaGrandMere
  • 10,265
  • 1
  • 33
  • 41
  • I wasn't using the TreeView click event I was using the MenuItem click event. But this helped to figure out my solution. the Treeview is always available and there is only one. So I just access it directly instead of trying to get it from the event handler parameters. – scott Dec 16 '11 at 14:28