Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming

How to change the background color on different lines of text in a TListBox

By Zarko Gajic, About.com

After dropping a TListBox on your form, you must change the Style property of the TListBox to lbOwnerDrawFixed. If you fail to change the Style property, the OnDrawItem event will never be called. Put the following code in the OnDrawItem event of your TListBox:

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.ListBox1DrawItem
   (Control: TWinControl; Index: Integer;
   Rect: TRect; State: TOwnerDrawState) ;
var
   myColor: TColor;
   myBrush: TBrush;
begin
   myBrush := TBrush.Create;
   with (Control as TListBox).Canvas do
   begin
     if not Odd(Index) then
       myColor := clSilver
     else
       myColor := clYellow;

     myBrush.Style := bsSolid;
     myBrush.Color := myColor;
     Windows.FillRect(handle, Rect, myBrush.Handle) ;
     Brush.Style := bsClear;
     TextOut(Rect.Left, Rect.Top,
             (Control as TListBox).Items[Index]) ;
     MyBrush.Free;
   end;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Is computer attached to a network?
« Deactivating the default context menu (on TWinControl descedants)

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TListBox
  6. How to change the background color on different lines of text in a TListBox

©2009 About.com, a part of The New York Times Company.

All rights reserved.