Reputation:
My Listview is setup in the details view with the following column headers:
Image Name || Image Location || Image Size || Image Preview
I would like to know if there is a way to draw an image in the 4th column there. The only way I know, is to set
this.listview1.OwnerDraw = true
this.listView1.DrawColumnHeader += new System.Windows.Forms.DrawListViewColumnHeaderEventHandler(listView1_DrawColumnHeader);
this.listView1.DrawItem += new System.Windows.Forms.DrawListViewItemEventHandler(listView1_DrawItem);
this.listView1.DrawSubItem += new System.Windows.Forms.DrawListViewSubItemEventHandler(listView1_DrawSubItem);
The problem with this is I have to handle ALL the listview drawing myself... I was wondering if there is a better way to draw in image to a subItem, or if there is a way to only handle the DrawSubItem event?
Upvotes: 5
Views: 19791
Reputation: 6882
ObjectListView (an open source wrapper around a .NET WinForms ListView) trivially supports drawing images in columns without having to do all the owner drawing yourself. The Data tab of the demo shows animated GIFs, which is a bit OTT but it will work equally well with static images.
With a few lines of code, this is what your ListView can look like:
(source: sourceforge.net)
Upvotes: 3
Reputation: 632
In listView1_DrawColumnHeader
and listView1_DrawItem
event handlers you should put this
e.DrawDefault = true;
It will use default drawing implementation for columns and items, all you have to do is write your own implementation only for subitems.
Upvotes: 1
Reputation: 7314
Building upon previous answers, here's a full VB.NET example:
Public Class MyListView : Inherits System.Windows.Forms.ListView
Public Sub New()
MyBase.New()
MyBase.OwnerDraw = True
End Sub
Protected Overrides Sub OnDrawSubItem(ByVal e As DrawListViewSubItemEventArgs)
If x Then ' condition to determine if you want to draw this subitem
' draw code goes here
Else
e.DrawDefault = True
End If
MyBase.OnDrawSubItem(e)
End Sub
Protected Overrides Sub OnDrawColumnHeader(ByVal e As DrawListViewColumnHeaderEventArgs)
e.DrawDefault = True
MyBase.OnDrawColumnHeader(e)
End Sub
Protected Overrides Sub OnDrawItem(e As System.Windows.Forms.DrawListViewItemEventArgs)
e.DrawDefault = True
MyBase.OnDrawItem(e)
End Sub
End Class
Upvotes: 0
Reputation: 12401
I just ran into this.
@zidane's answer is nearly correct. I want to post what actually needs to be done so people reading back later don't have to figure this out themselves.
Only handle DrawColumnHeader
using e.DrawDefault = true;
and the subitem drawing. In fact, if you set e.DrawDefault = true;
in the DrawItem
event, the DrawSubItem
event never fires, presumably on the assumption that you want to draw the whole row and don't care about the subitems.
The only real code is in DrawSubItem
, using this basic construction:
if (/* condition to determine if you want to draw this subitem */)
{
// Draw it
}
else
e.DrawDefault = true;
Upvotes: 8