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 Guide

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)

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

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

  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.