Reputation: 209
I,
I'm creating a VB Form with a ListView object containing Images of Excel, Word or Pdf Icons, with a link to the displayed document (to be made)
When compilating, the names of the documents are displayed in the listView but not the icons. Do you know what is missing in my code?
As far as I understand, the "ExtractAssociatedIcon" method needs the full path to the file, but it seems that no Icon is collected here.
Thanks
Imports System
Imports System.IO
Imports System.Drawing
[...]
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exePath As String
Dim exeIcon As Drawing.Icon
dirInfo = New DirectoryInfo("G:\XXX\XXX\XXX\XXX\XXX")
'We use this For...Each to iterate over the collection of files in the folder
For Each fileInfo In dirInfo.GetFiles
'We can only find associated exes by extension, so don't show any files that have no extension
If fileInfo.Extension = String.Empty Then
Else
'Use the function to get the path to the executable for the file
exePath = fileInfo.FullName
'Use ExtractAssociatedIcon to get an icon from the path
exeIcon = Drawing.Icon.ExtractAssociatedIcon(exePath)
'Add the icon if we haven't got it already, with the executable path as the key
If ImageList1.Images.ContainsKey(exePath) Then
Else
ImageList1.Images.Add(exePath, exeIcon)
End If
'Add the file to the ListView, with the executable path as the key to the ImageList's image
ListView1.View = View.LargeIcon
ListView1.Items.Add(fileInfo.Name, exePath)
End If
Next
Upvotes: 0
Views: 2481
Reputation: 9991
1) You need to set the SmallImageList and/or the LargeImageList property of the ListView
:
ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1
2) Put this at the top of your code. (Not in the For Each
loop)
ListView1.View = View.LargeIcon
3) Also, be sure that you don't add an empty icon, nor sets an invalid image key:
If (ImageList1.Images.ContainsKey(exePath)) Then
ListView1.Items.Add(fileInfo.Name, exePath)
ElseIf (Not exeIcon Is Nothing) Then
ImageList1.Images.Add(exePath, exeIcon)
ListView1.Items.Add(fileInfo.Name, exePath)
Else
ListView1.Items.Add(fileInfo.Name)
End If
Example
The following code is tested and works fine:
ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1
ListView1.View = View.LargeIcon
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exeIcon As System.Drawing.Icon
dirInfo = New DirectoryInfo("...")
For Each fileInfo In dirInfo.GetFiles
If (Not String.IsNullOrEmpty(fileInfo.Extension)) Then
exeIcon = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName)
If (ImageList1.Images.ContainsKey(fileInfo.FullName)) Then
ListView1.Items.Add(fileInfo.Name, fileInfo.FullName)
ElseIf (Not exeIcon Is Nothing) Then
ImageList1.Images.Add(fileInfo.FullName, exeIcon)
ListView1.Items.Add(fileInfo.Name, fileInfo.FullName)
Else
ListView1.Items.Add(fileInfo.Name)
End If
End If
Next
Upvotes: 1