C# WinForms - TreeView, Context Menu
-
05-07-2019 - |
Question
Suppose I am using a context menu to add child nodes to a treeview control.
(1) I am right-clicking on the node
(2)context menu pop up
(3)then I click "Add" menu item
(4)a dialogBox opens up
(5) I input the name in that DialogBox and press OK
(6) A new Node is created.
How can I get the reference of the current Node when I am clicking on the context menu item?
I need this coz the parent object is stored in the Tag property of the current node.
Solution
If you handle TreeNodeMouseClick
, then your TreeNodeMouseClickEventHandler
will be passed a TreeNodeMouseClickEventArgs
argument.
TreeNodeMouseClickEventArgs.Node will be the TreeNode reference you want. See the TreeNodeMouseClick
docs for an example similar to:
void treeView1_NodeMouseClick(object sender,
TreeNodeMouseClickEventArgs e)
{
TreeNode theTreeNodeIWant = e.Node
}
If you need to, you can store a reference in a member variable so another method can access it.
OTHER TIPS
You can get the mouse position from
System.Windows.Forms.Cursor.Position
Save this before showing the context menu.
Then use the method on the Treeview containing your items
GetChildAtPoint(Point)
and add a child below that.