How to get the TreeNode a context menu item is attached to

86 Views Asked by At

In a Winforms application, I have this code:

private void BtnNuevoGrupo_Click(object sender, EventArgs e)
{
    TreeNode newNode = TreDevices.Nodes[0].Nodes.Add("Nuevo grupo de validación");
    TreDevices.Nodes[0].Expand();
    TreDevices.SelectedNode = newNode;
    newNode.Tag = "IN:0";
    newNode.BeginEdit();
}

With that code, I am adding a tree node and starting edit immediately. Then, I have this code:

private async void TreDevices_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
      e.Node.ContextMenuStrip = new ContextMenuStrip();
      var itemEntrada = e.Node.ContextMenuStrip.Items.Add("Entrada");
      itemEntrada.Click += InOutItem_Click;
}

Finally, I have this code to do some action when the context menu item is clicked:

private async void InOutItem_Click(object? sender, EventArgs e)
{
    if (sender is not null)
    {
        var item = (ToolStripMenuItem)sender;
        ContextMenuStrip menu = (ContextMenuStrip)item.Owner;

        // HERE I NEED TO GET A REFERENCE TO THE TreeNode
    }
}

In InOutItem_Click I need to get a reference to the TreeNode that owns the menu. How can I do it?

I can only get a reference to the tree control by using item.Owner.SourceControl.

1

There are 1 best solutions below

0
On

Have you considered just using the Tag property of itemEntrada?

private void TreDevices_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
    e.Node.ContextMenuStrip = new ContextMenuStrip();
    var itemEntrada = new ToolStripMenuItem
    {
        Text = "Entrada",
        Tag = e.Node,
    };
    e.Node.ContextMenuStrip.Items.Add(itemEntrada);
    itemEntrada.Click += InOutItem_Click;
}

private void InOutItem_Click(object sender, EventArgs e)
{
    if ((sender is ToolStripMenuItem tsmi) && (tsmi.Tag is TreeNode node))
    {
        var item = (ToolStripMenuItem)sender;
        ContextMenuStrip menu = (ContextMenuStrip)item.Owner;

        MessageBox.Show($"Clicked {node.Text}");
    }
}

screenshot