user366312
user366312

Reputation: 17016

C# WinForms - TreeView, Context Menu

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.

Upvotes: 0

Views: 4989

Answers (2)

JeffH
JeffH

Reputation: 10482

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.

Upvotes: 7

Colin Gravill
Colin Gravill

Reputation: 4274

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.

Upvotes: 1

Related Questions