Category / Section
How to customize the contextmenu to display the name of the selected node when right clicked on it in WinForms TreeViewAdv?
1 min read
Customize the context menu
The user could customize the context menu to display the name of the selected node when right clicked on the SelectedNode by handling the MouseDown Event handler in the following way.The user have to get the right click point of the selectedNode.Then if the selectedNode is not equal to null, the a new menu item is created and added,such that the item displays the selectedNode's text name. For displaying only, the selectedNode text at a time when right clicked, the menu items must be cleared.
C#
private void treeViewAdv1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if(e.Button==MouseButtons.Right) { //Clear the contextMenu Menuitems this.contextMenu1.MenuItems.Clear(); this.treeViewAdv1.SelectedNode=this.treeViewAdv1.GetNodeAtPoint(new Point(e.X,e.Y)); //If the selected node is not equal to null, check for the condition if(this.treeViewAdv1.SelectedNode!=null) { //Create MenuItem for the SelectedNode MenuItem menuitem=new MenuItem(this.treeViewAdv1.SelectedNode.Text); this.contextMenu1.MenuItems.Add(menuitem); } } }
VB
Private Sub treeViewAdv1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) If e.Button=MouseButtons.Right Then 'Clear the contextMenu Menuitems Me.contextMenu1.MenuItems.Clear() Me.treeViewAdv1.SelectedNode=Me.treeViewAdv1.GetNodeAtPoint(New Point(e.X,e.Y)) 'If the selected node is not equal to null, check for the condition If Not Me.treeViewAdv1.SelectedNode Is Nothing Then 'Create MenuItem for the SelectedNode Dim menuitem As MenuItem = New MenuItem(Me.treeViewAdv1.SelectedNode.Text) Me.contextMenu1.MenuItems.Add(menuitem) End If End If End Sub