Author: Jonas Bilinkevicius
How to change the color of a specific subitem in a TListView.
Answer:
To change the color of a specific SubItem in a TListView all you have to do is to
put some code in the OnCustomDrawSubItems event of the TListView. Your probably
thinking of putting the OwnerDraw property of the ListView to True...
don't do this, yes I know normally it should be set to True, but in case of a
TListView this is not the case...a bug somewhere in Delphi. Unlike the OnCustomDraw
the OnCustomDrawSubItems event is sent no matter the state of the OwnerDraw
property.
The OnCustomDrawSubItems is fired prior to drawing the SubItem on the TListView.
To alter the default drawing process at other stages (e.g. after the SubItem is
drawn,... .), you must use the OnAdvancedCustomDrawSubItem event.
You can put code here to change the appeance of the SubItems, the ViewStyle of the
TListView must be set to vsReport in order for this to function correctly.
Then you can use the canvas of the ListView as a drawing surface.
Let's say you want the font color of a SubItem to turn red whenever it's below is
negative then put the following code in the OnCustomDrawSubItems event:
1 2 procedure TForm1.ListViewCustomDrawSubItem(
3 Sender: TCustomListView; Item: TListItem; SubItem: Integer;
4 State: TCustomDrawState; var DefaultDraw: Boolean);
5 begin6 //Check if the value of the third column is negative,7 //if so change it's font color to Red (clRed).8 if SubItem = 3 then9 try10 if StrToInt(Item.SubItems.Strings[SubItem - 1]) < 0 then11 Sender.Canvas.Font.Color := clRed;
12 except13 on EConvertError do14 next;
15 end;
16 end;
Used Parameters:
Sender : Specifies the ListView that owns the SubItems
Item : Is the current Item being drawn
SubItem: Index of the SubItem of the ListItem (Item) in its SubItems property
State : Indicates various attributes that affect the way the SubItem is drawn
DefaultDraw: Set it to False to prevent the ListView from adding the SubItem's text
after the event handler exits.
Tested with Delphi 6 Professional on Windows 2000 Professional.