Friday, July 3, 2009

Context menu display by right click on tree view node

This VB.NET Code explains how to display a context menu when right click on the treeview node.

To associate a ContextMenu with a particular form or control we need to set the ContextMenu property of that form or control to the appropriate menu.

By default, right-clicking on a node does not set focus to that node.

We need to explicitly set focus to the node clicked on.

This is especially important when you want to use a ContextMenu control and associate it with a TreeView.

Drag treeview control and place on the Form and name it as TreeView1.

Drag ContextMenuStrip and place on the Form and name it as MyContextMenu.

Add two items Menu1, Menu2.

[CODE]

'Populating the treeview
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim tnode As New TreeNode()

Me.TreeView1.Nodes.Clear()

With Me.TreeView1.Nodes
tnode = .Add("", "Nodes", 0)
tnode.Nodes.Add("", "Node 1", 0)
tnode.Nodes.Add("", "Node 2", 0)
End With
TreeView1.ExpandAll()

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub


'Display context menu when right click on the tree view node
Private Sub TreeView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TreeView1.MouseDown

Dim NodeClicked As TreeNode

' Get the node clicked on
NodeClicked = Me.TreeView1.GetNodeAt(e.X, e.Y)

If e.Button = Windows.Forms.MouseButtons.Right Then

' By default, right-clicking on a node does not set

' focus to that node. This is especially important when

' you want to use a ContextMenu control and associate

' it with a TreeView. This code shows how to do it.


Me.TreeView1.SelectedNode = NodeClicked

'Display the context menu
MyContextMenu.Show(TreeView1, New Point(e.X, e.Y))


End If
End Sub

Private Sub Menu1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Menu1.Click
MsgBox("I am Menu1")
End Sub

Private Sub Menu2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Menu2.Click
MsgBox("I am Menu2")
[/CODE]

When you right click on treeview nodes the context menu will appear.

For sample, I am displaying message box when they click on the menu. But you can change according to your need.

1 comment: