Click here to Skip to main content
Click here to Skip to main content

ListView with Image on SubItems

By , 4 Jul 2004
 

Introduction

This article describes how to implement ListView with image on subitems. It's very useful in programs that need to show the status of several items.

OAKListView control

This class inherits from the ListView class.

Using the code

Make some change in your code. Add a traditional ListView control to your form and make the changes (in black) as below:

/****************************************************************************/
/// 
/// Summary description for Form1.
/// 
public class Form1 : System.Windows.Forms.Form
{
    // Change this line...
    private System.Windows.Forms.ListView listView1;
    private System.Windows.Forms.ColumnHeader columnHeader1;
    private System.Windows.Forms.ColumnHeader columnHeader2;

/// 
/// Summary description for Form1.
/// 
public class Form1 : System.Windows.Forms.Form
{
    // Like this line...
    private OAKControls.OAKListView listView1;
    private System.Windows.Forms.ColumnHeader columnHeader1;
    private System.Windows.Forms.ColumnHeader columnHeader2;

/****************************************************************************/

/****************************************************************************/
#region Windows Form Designer generated code
/// 
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// 
private void InitializeComponent()
{
    this.components = new System.ComponentModel.Container();
    System.Resources.ResourceManager resources = 
      new System.Resources.ResourceManager(typeof(Form1));
    // Change this line...
    this.listView1 = new System.Windows.Forms.ListView();

#region Windows Form Designer generated code
/// 
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// 
private void InitializeComponent()
{
    this.components = new System.ComponentModel.Container();
    System.Resources.ResourceManager resources = 
      new System.Resources.ResourceManager(typeof(Form1));
    // Like this line...
    this.listView1 = new OAKControls.OAKListView();

/*****************************************************************************/

Changing image on subitem

OAKListView.LV_ITEM lvi = new OAKListView.LV_ITEM();
// Row of the item
lvi.iItem = 5; 
// Column of the item
lvi.iSubItem = 5;
lvi.pszText = "OAKListView-" + I.ToString();
//Here you pass the mask of the item. In this case 
//the mask is the both, Image and the text
lvi.mask = OAKListView.LVIF_IMAGE | OAKListView.LVIF_TEXT; 
// Image index on imagelist
lvi.iImage = 1;
// Sending a message to make the changes
OAKListView.SendMessage(listView1.Handle, 
         OAKListView.LVM_SETITEM, 0, ref lvi);

Conclusion

Most of the functionalities have been described here.

I do not guarantee that this control works 100%. If you find mistakes, you can correct them. This control is not a final release and you can send me mails with explanations if you find bugs or mistakes, and join the modifications if you did them.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Carlos Carvalho
Web Developer
Australia Australia
Carlos Carvalho is a developer and trainer based in Brasil.
He has been developing applications and components since 1995.
He has a large experience in development of several platforms including embedded systems.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questiondid not appear imagens in subitensmembervinao9-Jan-12 7:06 
I did the donwload source, but when I clicked in "Click to add image on SubItems". Its appear image only item in listview.
AnswerRe: did not appear imagens in subitensmemberEric-Paul22-Jan-12 0:37 
Just read the message "Fix for .NET 2.0" and you'll be fine.
GeneralRe: did not appear imagens in subitensmemberatifamin20023-Nov-12 2:30 
Where is fix for .net 2.0? I have same problem
Generalabout parammemberjason_mf6-Mar-11 21:23 
declared numbers of "LVS_EX_...".
But used only 5.
 
I tried to just pass "LVS_EX_SUBITEMIMAGES " to "lParam":
Message.Create(this.Handle, LVM_GETEXTENDEDLISTVIEWSTYLE, IntPtr.Zero, (IntPtr)LVS_EX_SUBITEMIMAGES);
It can run also.
 
If I just pass "LVS_EX_SUBITEMIMAGES " to Message's Create Method,
the listview wehther will has any problem?
 
What meaning each of these Constant?
The values can be custom?
 
public const Int32 LVM_FIRST = 0x1000;
public const Int32 LVM_GETITEM = LVM_FIRST + 5;
public const Int32 LVM_SETITEM = LVM_FIRST + 6;
public const Int32 LVIF_TEXT = 0x0001;
public const Int32 LVIF_IMAGE = 0x0002;
 
public const int LVW_FIRST = 0x1000;
public const int LVM_GETEXTENDEDLISTVIEWSTYLE = LVW_FIRST + 54;
 
public const int LVS_EX_GRIDLINES = 0x00000001;
public const int LVS_EX_SUBITEMIMAGES = 0x00000002;
public const int LVS_EX_CHECKBOXES = 0x00000004;
public const int LVS_EX_TRACKSELECT = 0x00000008;
public const int LVS_EX_HEADERDRAGDROP = 0x00000010;
public const int LVS_EX_FULLROWSELECT = 0x00000020; // applies to report mode only
public const int LVS_EX_ONECLICKACTIVATE = 0x00000040;
GeneralThank youmembervherisse25-Feb-09 10:26 
Thank you Carlos for writing this article.
QuestionOakListView for VB?memberUweSch13-Feb-08 3:35 
Hi,
 
i'm looking for some similar in vb.net.
Is there a sample anywhere?
 
Thanks for help.
 

Sincerely,
Uwe
AnswerRe: OakListView for VB?memberdan neely10-Apr-09 10:34 
Put the .cs file in a C# project, and add a reference to it from your vb project(s).
 
Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots.
-- Robert Royall

Questionhow to chande background colormembernits_bhole17-Dec-06 21:32 
hi,
i hav a query..
when i click on a image it show a blue strip all over the row..
but is it possible when i click on image then the blue color should not appear on image itselt..
it can appear on text part..
 
how can it be done???
 
Nits

QuestionSubitem icons not appearingmemberbs999930-Nov-06 5:15 
I have the class added to my own but it doesn’t appear to be showing any icons for subitems. I noticed that if I have the Visual Studio .Net 2003 designer attach an image list to the Oak List View then absolutely no icons are shown, not even within column 0. However if I remove this and manually insert the listview – imagelist association within the Form_Load then the column 0 icon appears however still no subitem icons appear. Im using .Net Framework 1.1 on VS Studio .Net 2003 C#
 

Very odd. Was wondering if there was some subtle pattern I was missing.
 


GeneralText color / Background colormemberobsy1-Jul-06 4:54 
Hi,
Is there a way to change the text color on subitems ?
Also, the background color !?
 
Thanx.
GeneralRe: Text color / Background colormemberJared James Sullivan13-Nov-06 16:40 
You should be able to do that with no additional problems.
 
MyListview.items(0).backcolor =color.black
 
Although, if you wish to change indvidual forecolor on different subitems you may need to first set this property...
 
MyListview.items(0).UseItemStyleForSubItems = False
 
As this property forces all subitems to be same by default.
 
Jared Sullivan
GeneralRe: Text color / Background colormemberAcerDad30-Nov-06 12:29 
How about changing the color (or background color) of only PART of a subitem's text?
 
I have a project where I use a listview to show a list of files to be scanned. If the file name contains one of the search strings, I want to highlight the part of the filename that matches, not the entire filename which results from using the subitem.ForeColor property.
 
Eric
 
Eric

QuestionWith C# 2.0 Fix, Still No Subitem Icons?memberEarlD11-May-06 15:51 
I made the 2.0 fix suggested to the constructor, but when I run the sample app, I still get no subitem images.
 
Am I the only one that can't get it working? Smile | :)
 
thanks
AnswerRe: With C# 2.0 Fix, Still No Subitem Icons?memberEarlD11-May-06 15:53 
My apologies. I have it working now.
 
thanks
GeneralRe: With C# 2.0 Fix, Still No Subitem Icons?memberklimb902-Jan-08 18:53 
Would you mind sharing what it was that made it go from not-working to working..
I have made the change to the constructor to no avail.
What other step am I missing?
AnswerRe: With C# 2.0 Fix, Still No Subitem Icons?memberBertrand Jobert27-Feb-09 1:56 
The solution is to override the OnHandleCreated base method instead of having the code in the constructor:
 
	public OAKListView() : base()
	{
	}
 
	/// <summary>
	/// Changing the style of listview to accept image on subitems
	/// </summary>
        protected override void OnHandleCreated(EventArgs e)
	{
        	base.OnHandleCreated(e);
		// Change the style of listview to accept image on subitems
		System.Windows.Forms.Message m = new Message();
		m.HWnd = this.Handle;
		m.Msg = LVM_GETEXTENDEDLISTVIEWSTYLE;
		m.LParam = (IntPtr)(LVS_EX_GRIDLINES | 
								LVS_EX_FULLROWSELECT | 
								LVS_EX_SUBITEMIMAGES | 
								LVS_EX_CHECKBOXES | 
								LVS_EX_TRACKSELECT);
		m.WParam = IntPtr.Zero;
		this.WndProc(ref m);
	}

 
Bertrand Jobert

GeneralRe: With C# 2.0 Fix, Still No Subitem Icons?memberdanceinrain1-Mar-09 21:23 
it really worked, thanks.
QuestionIndenting SubItem ?memberPandaPKH17-Apr-06 23:19 
I wan't to indent icons and text in subitems
any idea?
thx
AnswerRe: Indenting SubItem ?memberyazoox24-Apr-06 21:09 
I also care about the problem indent.
As the matter of fact, I only want to add icon to subitem, but don't want icon showed in the first column.
But, even though the icon do not show in the first column, the indent still exists. How to delete the indent?
 
thanks a lot.
Laugh | :laugh:
GeneralRe: Indenting SubItem ?memberSynetech1-Oct-08 17:13 
Did you ever find a solution to this? I too want to put images in subitems, but not the first column, and don’t want a blank icon in the column 0.
 
--
Synetech

GeneralRe: Indenting SubItem ?memberJohn Simmons / outlaw programmer21-Feb-10 11:48 
I know this is a little late, but you could make the first column hidden, and only use subitems... Thatshould give you what you want.
.45 ACP - because shooting twice is just silly
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

GeneralRe: Indenting SubItem ?memberSynetech21-Feb-10 11:55 
It’s never too late. Smile | :)
 
I suppose using sub-items only is a work-around (presumably making column 0 empty). Unfortunately it renders jump-keys useless. I am almost certain that I have read of the possibility to customize jump-keys, but I can’t find it now. If it is indeed possible, then a hidden column 0 would be a practical work-around.
--
Synetech

QuestionHow to Find Item with Textmemberrm_pkt2-Apr-06 19:09 
Very good article.
I would like to add a functionality to find item text within the ListView sub items.
I don't know how to add such funtionality with this Control.Frown | :(
 
For Normal Listview, it works fine with FindItemWithText() method.
 
any help would be appriciated.
 
Thanks in advance.
 

 
rm_pkt
Generalhere is the vb.net version of this smart classmemberale75fly21-Mar-06 16:32 
Imports System
Imports System.Threading
Imports System.IO
Imports System.Drawing
Imports System.Diagnostics
Imports System.Data
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
 
Public Class OAKListview
Inherits System.Windows.forms.ListView
 

'namespace OAKControls
'
'Summary description for OAKListView.
'

 
Public Structure LV_ITEM
Public mask As UInt32
Public iItem As Int32
Public iSubItem As Int32
Public state As UInt32
Public stateMask As UInt32
Public pszText As String
Public cchTextMax As Int32
Public iImage As Int32
Public lParam As IntPtr
End Structure
 
Public Const LVM_FIRST As Int32 = &H1000
Public Const LVM_GETITEM As Int32 = LVM_FIRST + 5
Public Const LVM_SETITEM As Int32 = LVM_FIRST + 6
Public Const LVIF_TEXT As Int32 = &H1
Public Const LVIF_IMAGE As Int32 = &H2
 
Public Const LVW_FIRST As Integer = &H1000
Public Const LVM_GETEXTENDEDLISTVIEWSTYLE As Integer = LVW_FIRST + 54
 
Public Const LVS_EX_GRIDLINES As Integer = &H1
Public Const LVS_EX_SUBITEMIMAGES As Integer = &H2
Public Const LVS_EX_CHECKBOXES As Integer = &H4
Public Const LVS_EX_TRACKSELECT As Integer = &H8
Public Const LVS_EX_HEADERDRAGDROP As Integer = &H10
Public Const LVS_EX_FULLROWSELECT As Integer = &H20 ' applies to report mode only
Public Const LVS_EX_ONECLICKACTIVATE As Integer = &H40
 
'///
'/// Changing the style of listview to accept image on subitems
'///

Public Sub New()
'// Change the style of listview to accept image on subitems
Dim m As System.Windows.Forms.Message = New Message
m.HWnd = Me.Handle
m.Msg = LVM_GETEXTENDEDLISTVIEWSTYLE
m.LParam = New IntPtr(LVS_EX_GRIDLINES Or LVS_EX_FULLROWSELECT Or LVS_EX_SUBITEMIMAGES Or LVS_EX_CHECKBOXES Or LVS_EX_TRACKSELECT)
m.WParam = IntPtr.Zero
Me.WndProc(m)
End Sub
 

Public Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" _
(ByVal hWnd As IntPtr, _
ByVal Msg As Integer, _
ByVal wParam As IntPtr, _
ByVal lParam As IntPtr) As Integer
 

Public Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" _
(ByVal hWnd As IntPtr, _
ByVal Msg As Int32, _
ByVal wParam As Int32, _
ByRef lParam As LV_ITEM) As Boolean
 
End Class
GeneralIcons disapearing after form hide/showmemberjared james sullivan13-Feb-06 15:41 
Hi,
 
Thanks for .NET 2.0 fix, anyone tried hiding and redisplaying a form?
 

 
Jared
GeneralRe: Icons disapearing after form hide/showmemberjared james sullivan13-Feb-06 15:53 
I have a nice hack.
 
mdichild.location = new location(0, 1000) 'hide
mdichild.location = new location(0,0) 'show
 
Jared
GeneralRe: Icons disapearing after form hide/showmemberjared james sullivan13-Feb-06 16:26 

That throws scroll bars out.
 
Have to re-load all images again
GeneralFix for .NET 2.0membershivpal4-Feb-06 6:30 
Following changes will fix it to work on .NET 2.0 framework.
1) change the constructor as given below
2) add the event handler for handleCreated as given below
 
public OAKListView()
{
this.HandleCreated += new EventHandler(OAKListView_HandleCreated);
}
 
void OAKListView_HandleCreated(object sender, EventArgs e)
{
System.Windows.Forms.Message m = new Message();
m.HWnd = this.Handle;
m.Msg = LVM_GETEXTENDEDLISTVIEWSTYLE;
m.LParam = (IntPtr)(LVS_EX_GRIDLINES |
LVS_EX_FULLROWSELECT |
LVS_EX_SUBITEMIMAGES |
LVS_EX_CHECKBOXES |
LVS_EX_TRACKSELECT);
m.WParam = IntPtr.Zero;
this.WndProc(ref m);
}
GeneralRe: Fix for .NET 2.0memberyazoox5-Apr-06 21:42 
yeah.
That's Ok.
 
could you tell us why?
Smile | :)
GeneralRe: Fix for .NET 2.0memberMalleesh5-Dec-06 23:07 
Thanks for the posting. It helped me a lot in a crucial moment. But it would be highly useful if u could share the idea behind this fix
GeneralRe: Fix for .NET 2.0memberroboman29-May-08 21:35 
THANKS..
GeneralRe: Fix for .NET 2.0memberBabybaer2-Nov-09 22:05 
Works to .NET 3.5
THX
 
Mfg@Babybaer

GeneralImages are left-justifiedmemberergentrasse15-Dec-05 6:30 
Is there a way to center the image in the subitem? Supossing no text is requiered.
GeneralNo Image shown in SubItems column in c# 2.0memberDonald Man6-Oct-05 21:45 
I found that it doesn't work if it is complied in .net framework 2.0. There is no image in any subitems columns.
GeneralRe: No Image shown in SubItems column in c# 2.0memberklemenz3-Nov-05 5:28 
Confirming that.
GeneralRe: No Image shown in SubItems column in c# 2.0membervovototo24-Dec-05 1:21 
Yes I confirm too
Nobody find a way to fix the control for .net 2.0 ?
Thanks
GeneralRe: No Image shown in SubItems column in c# 2.0memberDustin Aleksiuk13-Jan-06 13:52 
Ditto! (Just being helpful)
GeneralRe: No Image shown in SubItems column in c# 2.0membershivpal4-Feb-06 4:50 
Same here!!!
 
-SP
GeneralRe: No Image shown in SubItems column in c# 2.0memberyazoox5-Apr-06 21:38 
same here
QuestionRe: No Image shown in SubItems column in c# 2.0memberCélio3-Jan-07 23:04 
I wonder if any body has the sample working in C# .Net 2.0?
If so, can you email me the sample?
 
Cool | :cool: Thanks Cool | :cool:
 
CeliSoft

GeneralRe: No Image shown in SubItems column in c# 2.0memberzobis16-May-08 10:40 
to make it work,make the follwing changes in code:
 
public OAKListView()
{
this.HandleCreated += new EventHandler(OAKListView_HandleCreated);
}
 
void OAKListView_HandleCreated(object sender, EventArgs e)
{
System.Windows.Forms.Message m = new Message();
m.HWnd = this.Handle;
m.Msg = LVM_GETEXTENDEDLISTVIEWSTYLE;
m.LParam = (IntPtr)(LVS_EX_GRIDLINES |
LVS_EX_FULLROWSELECT |
LVS_EX_SUBITEMIMAGES |
LVS_EX_CHECKBOXES |
LVS_EX_TRACKSELECT);
m.WParam = IntPtr.Zero;
this.WndProc(ref m);
}
 
Zobis.
GeneralRe: No Image shown in SubItems column in c# 2.0memberSteven Nicholas28-Feb-09 22:33 
That works. Thanks.
QuestionHow to get the text of a listview item.memberdan neely23-Sep-05 9:25 
I can get the symbol of an item but sendmessage returns an lvi with a null string for the text item. This code is essentially the same as what is used to set the text, except that it sends a different message.
 
OAKListView.LV_ITEM lvi = new OAKListView.LV_ITEM();
lvi.iItem = index;
lvi.iSubItem = column;
lvi.mask = OAKListView.LVIF_IMAGE | OAKListView.LVIF_TEXT;
// Send the message to get the icon and text
OAKListView.SendMessage(handle, OAKListView.LVM_GETITEM, 0, ref lvi);

GeneralAfter Sorting - Images are GonememberSumeet_CodeProject26-Jul-05 2:00 
This is an amazing piece of code.. I am able to show the icons in the SubItems. Now the problem is that when I try to sort the ListView on ColumnHeader Click, the Icons are lost. The Icons are not visible anymore.
 
I have implemented the IComparer class as suggested on the Microsoft Site for sorting the Listview Columns.
 
--------------------------------
This is the code for sorting the Listview Column:
--------------------------------
Public Class ColumnSorter
Implements IComparer
Private m_SortOrder As SortOrder
Private m_CurrentColumn As Integer
 
Sub New(ByVal p_SortOrder As SortOrder, ByVal p_Column As Integer)
m_SortOrder = p_SortOrder
m_CurrentColumn = p_Column
End Sub
 
Public Function Compare(ByVal p_Actual As Object, ByVal p_Desried As Object) As Integer Implements System.Collections.IComparer.Compare
If m_SortOrder = SortOrder.Ascending Then
If TypeOf p_Actual Is ListViewItem Then
Return String.Compare(DirectCast(p_Actual, ListViewItem).SubItems(m_CurrentColumn).Text, _
DirectCast(p_Desried, ListViewItem).SubItems(m_CurrentColumn).Text)
Else
End If
Else
If TypeOf p_Actual Is ListViewItem Then
Return String.Compare(DirectCast(p_Desried, ListViewItem).SubItems(m_CurrentColumn).Text, _
DirectCast(p_Actual, ListViewItem).SubItems(m_CurrentColumn).Text)
Else
End If
End If
End Function
End Class
 
--------------------------------
// End of Code
--------------------------------
 
Can you please suggest how to have the Images back in the ListView after sorting is done...???
 
I'll be very greatful to you.
 
Thanks in advance..!
 


 
Sumeet Mahajan
GeneralRe: After Sorting - Images are Gonememberdan neely23-Sep-05 9:06 
I had problems with a comparer screwing up images as well. I ended up working around the problem with images not showing up by creating a new comparer every time a column was clicked, and then setting the reference to it back to NULL at the end of the column click event.
 
Unfortunately this class is as buggy as it it cool.
GeneralVB.Net versionmemberj1webb4-Mar-05 13:58 
Does anyone know whether a vb.net version was ever created. If so, does anyone know where to find it.
 
Also, has anyone found anyother way to add images to subitems in a listview. I have been searching and I have not found anything yet.
GeneralJuste a detail &amp; image cropmemberStyx3122-Feb-05 4:27 
The const you've used is named as follow :
 
public const int LVM_GETEXTENDEDLISTVIEWSTYLE = LVW_FIRST + 54;
 
But in CommCtrl.h, this const is LVM_SETEXTENDEDLISTVIEWSTYLE.
 
Another problem is that subitems pictures are cropped.
 
The most left pixel is not displayed. In your demo, images have a 1px left blank column, so render is ok. I try to find a workaround in API for this issue.
 
Anyway, good job Smile | :)
GeneralImagelist controlmemberDaap16-Dec-04 2:00 
Eek! | :eek: Little tip after I tried this code: make sure that in the InitializeComponent function, the ImageList's properties are set before the ListView's, otherwise the ListView won't show any images.

Generaldon't want image in first columnmemberBlackDice15-Nov-04 9:10 
Hello, I've used some examples from your code to put images in the subitems of my listview. That works fine. But I don't want images in the first column and it puts a blank space in front of the text in the column. Do you know how to get around this? Thanks. Also, I'm giving your code a 5!
 
If I write code in my sleep, does that make me brilliant, or just a lazy programmer?
 
My articles
 
www.stillwaterexpress.com
 
BlackDice - the programmer formerly known as bdiamond
GeneralRe: don't want image in first columnmemberobsy29-Jun-06 0:53 
Any clues would help us a lot.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 5 Jul 2004
Article Copyright 2004 by Carlos Carvalho
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid