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 do
begin
// put out lines in alternating colors
if not 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 }