Add Icon to Treeview node on the fly (ExtractAssociatedIcon)

sputnik75043

Member
Joined
Aug 28, 2010
Messages
13
Programming Experience
Beginner
As I'm adding a file path (not from a folder) to a treeview, how can I use ExtractAssociatedIcon to get an Icon and place it as the image for that node?

I know you can use an ImageList, but in this scenario, it would be added on the fly and not using a list.....
 
Yeah, you add it to the list on the fly. You create the Icon, Add it to the Images collection of the ImageList and then set the ImageKey or ImageIndex of the TreeNode appropriately. For instance, if you want to use the last item added then the index will be one less than the Count of the list.
 
Hi,

To add to what has already been said and since you are getting file Icons, I would suggest that you only add Unique File Icons for each file type as you encounter them to minimise the number of Icons that are added to the ImageList.

You can do this be Adding a Key value, being the file extension, to the ImageList when adding the Icons. This can then be tested for when you add each file to the TreeView and either extract the correct Icon Index using its Key or add the Icon and then retrieve the Icon Index for that Image. i.e:-

Check for each Icon and add it if necessary:-
VB.NET:
Dim fExtension As String = Path.GetExtension(fName)
 
If IsNothing(ImageList1.Images(fExtension)) Then
  Dim myIcon As Icon = Icon.ExtractAssociatedIcon(fName)
  ImageList1.Images.Add(fExtension, myIcon)
End If

Get the Icon Index for the TreeView:-
VB.NET:
.ImageIndex = ImageList1.Images.IndexOfKey(fExtension)

Hope that helps.

Cheers,

Ian
 
The one change I'd make to Ian's suggestion is, instead of this:
VB.NET:
If IsNothing(ImageList1.Images(fExtension)) Then
use this:
VB.NET:
If Not ImageList1.Images.ContainsKey(fExtension) Then
 
I got it working, but when I click on any node, the icon changes to the first node's icon. (The imageIndex of the Treeview defaults to 0 in the Properties window, and I can't change that)
Any ideas why?
 
Hi,

Since your TreeView will have the default ImageIndex and the default SelectedImageIndex properties for all nodes set to 0, when you click on the Node it will use index 0 of the ImageList as the image to be displayed when you click on the node which is your Root Node image.

To get round this you need to explicitly set the SelectedImageIndex when adding your nodes. i.e:-

VB.NET:
.Nodes.Add("NodeKey", "NodeName", <ImageIndex>, <SelectedImageIndex>)

Hope that helps.

Cheers,

Ian
 
Back
Top