Display a TListBox with alternating colors (custom drawn)
This article has not been rated yet. After reading, feel free to leave comments and rate it.
Question:
I'd like my TListBox to display rows alternating on white and silver background. How can I do this?
Answer:
Select the listbox style lbOwnerDrawFixed in the object inspector. Then add the following procedure and link it to the OnDrawItem event.
procedure TForm1.ListBox1DrawItem(Control: TWinControl; index: integer; Rect: TRect;
State: TOwnerDrawState);
var
ListColor: TColor;
ListBrush: TBrush;
begin{ TForm1.ListBox1DrawItem }// create a brush to paint the item's background
ListBrush := TBrush.Create;
// get a canvas to draw - this is a canvas for the complete listbox!
with (Control as TListBox).Canvas dobegin// put out lines in alternating colors
ifnot Odd(index) then
ListColor := clSilver;
else
ListColor := clWhite;
ListBrush.Style := bsSolid;
ListBrush.Color := ListColor;
Windows.FillRect(Handle, Rect, ListBrush.Handle);
Brush.Style := bsClear;
// write out the text
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[index]);
ListBrush.Free
end; { with (Control as TListBox).Canvas }end; { TForm1.ListBox1DrawItem }
You don't like the formatting? Check out SourceCoder then!
Comments:
2008-10-01, 23:15:12
anonymous from India
After this, my selection color is not showing:(
2008-10-01, 23:16:37
anuraagv@triologic.net from India
Sorry i forgot to add email address.
By the way when I select an item, the item is selected but it looks like selection is only disabled.