0

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.

jstuardo
  • 3,901
  • 14
  • 61
  • 136
  • The TreeView has a `HitTest()` for that -- Why are you creating a new ContextMenuStrip for each Node? Can't you use just one? – Jimi Feb 06 '23 at 18:55
  • Use a lambda expression to capture the treenode. itemEntrada.Click += (s, ea) => EntradaClick(e.Node); and replace InOutItem_Click with void EntradaClick(TreeNode node) {} – Hans Passant Feb 06 '23 at 19:07
  • @Jimi Because each node represents hardware devices. The context menu has 2 options, IN and OUT with a checkmark to the left of the option depending if the device is for input or for output. The user should be able to change one device from OUT to IN or from IN to OUT,. – jstuardo Feb 06 '23 at 20:39

1 Answers1

0

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

IVSoftware
  • 5,732
  • 2
  • 12
  • 23