
HOW TO: Set SubItem icons in report-style ListView controls
I've done some more fooling around with the ListView control and I've
figured out how to set the icons on sub-items in a report-style ListView
control. The technique requires comctl32.dll version 4.70 (the version
shipped with Internet Explorer 3.0) or later.
The basics of setting up a ListView to display sub-item icons are well
documented on Randy Birch's VBnet site
( http://www.*-*-*.com/ ), in the Common
Controls section of his Code Library. Randy's article describes how to
display the icons, but in his example, the icons that appear are the same
as the primary ListItem's icon--which, as he admits, is pretty useless.
The code below expands on his original article to allow you to
programmatically set the sub-item icons to whatever you want. It contains
the bare minimum needed to demonstrate the technique, but it can be easily
extended.
To begin, drop a ListView control and an ImageList control onto a form.
Add two 16x16 images to the ImageList. Set the ListView to display itself
in report style, add two column headers, then bind the ImageList control
to the ListView as the small icon image list.
Now paste the following code into the form's code window:
Option Explicit
Private Type LVITEM
Mask As Long
Item As Long
SubItem As Long
State As Long
StateMask As Long
Text As String
TextMax As Long
Image As Long
Param As Long
Indent As Long
End Type
Private Const LVM_FIRST = &H1000&
Private Const LVM_SETITEM = (LVM_FIRST + 6)
Private Const LVM_SETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 54)
Private Const LVM_GETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 55)
Private Const LVS_EX_SUBITEMIMAGES = &H2&
Private Const LVIF_IMAGE = &H2&
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Any) As Long
Private Sub Form_Load()
Dim LV As LVITEM
Dim lStyle As Long
Dim li As ListItem
' Add a ListItem
Set li = ListView1.ListItems.Add(, , "Item 1", , 1)
li.SubItems(1) = "SubItem 1"
' Set the ListView style to show sub-item images
lStyle = SendMessage(ListView1.hwnd, LVM_GETEXTENDEDLISTVIEWSTYLE, 0, _
ByVal 0&)
lStyle = lStyle Or LVS_EX_SUBITEMIMAGES
SendMessage ListView1.hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, ByVal _
lStyle
' Change the ListItem's sub-item image
With LV
.Mask = LVIF_IMAGE
.Item = li.Index - 1
.SubItem = 1 '1-based index of sub-item
.Image = 1 '0-based index of list image
End With
SendMessage ListView1.hwnd, LVM_SETITEM, li.Index - 1, LV
End Sub
When run, this code will display a single ListItem with the first image as
the item's icon and the second image as the sub-item's icon.
--