Introduction
In general, we can use only one image with each TreeNode
. There may be cases when we need multiple images, two, three, or more. We may also want to perform different operations on click of different images. Applying some trick, our single image can work as multiple images like I did in the example of this article. You just have to merge those images using any image editing software, i.e. Photoshop. This can be done by using ImageList
in .NET, assign that to TreeView
.
Using the Code
Identifying and performing operations on those images is as easy as adding images. Just work with TreeView
’s NodeMouseClick
event as below…
Private Sub trvMain_NodeMouseClick(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) _
Handles trvMain.NodeMouseClick
Dim x = e.Node.Bounds.X
Dim y = e.Node.Bounds.Y
Dim h = e.Node.Bounds.Y + e.Node.Bounds.Height
If e.X > x - 18 And e.X < x - 3 Then
If e.Y > y And e.Y < h Then
If e.Node.Nodes.Count = 0 Then
MsgBox(e.Node.Text + " Form")
End If
End If
ElseIf e.X > x - 35 And e.X < x - 18 Then
If e.Y > y And e.Y < h Then
MsgBox(e.Node.Text + " Document")
End If
End If
End Sub
In the beginning of this subroutine, we have recognized the bounds of the current TreeNode
. Then we have to check the location of mouse click, if the mouse was clicked on Document Image, then Else
part of IF…Else
statement will get true
, and if mouse was clicked on Form Image then IF
part of IF…Else
statements will get true
. In both cases, we can perform any operation, while I just show a message.
The next thing is if you don't want the same image for each TreeNode
, i.e. you want to change images of TreeNode
s which have children. Do it during runtime, when page loads, by changing the ImageIndex
property of those nodes.
Private Sub Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
For Each node As TreeNode In trvMain.Nodes
If node.Nodes.Count > 0 Then
node.ImageIndex = 1
node.SelectedImageIndex = 1
checkChild(node)
End If
Next
End Sub
Private Sub checkChild(ByVal nod As TreeNode)
For Each node As TreeNode In nod.Nodes
If node.Nodes.Count > 0 Then
node.ImageIndex = 1
node.SelectedImageIndex = 1
checkChild(node)
End If
Next
End Sub
Points of Interest
You can use any number of images, the sole thing you have to do is merge them using any image editing software. Also remember when you are checking for mouse click position that you must know the exact image size, so that you can easily apply that into if...else
conditions.
Final Words
I hope you will find this article helpful. For more information, you can check out the demo program available in the downloads section or you can contact me by leaving a message in the comments section below. Good luck!
History
- 14th June, 2008: Initial post