DelphiFAQ Home Search:

Display a TListBox with alternating colors (custom drawn)


commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.


I'd like my TListBox to display rows alternating on white and silver background. How can I do this?


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);
  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
    // put out lines in alternating colors
    if not Odd(index) then
      ListColor := clSilver;
      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]);

  end; { with (Control as TListBox).Canvas }
end; { TForm1.ListBox1DrawItem }
You don't like the formatting? Check out SourceCoder then!
Content-type: text/html


2008-10-01, 23:15:12
anonymous from India  
After this, my selection color is not showing:(
2008-10-01, 23:16:37 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.
2012-10-29, 05:42:21
anonymous from China  



NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: