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

TListBox with Radio Buttons

By Zarko Gajic, About.com

Radio Buttons in List Box

Delphi's TListBox VCL component displays a collection of items in a scrollable list. The MultiSelect property determines if a user can select more than one item. When MultiSelect is set to false (default state) a ListBox acts as a TRadioButton list container (similar to TRadioGroup).

Here's how to draw a radio button for each of the items in a List Box (meaningful only if MultiSelect is false) :

Note: Drop a TListBox on a Form, add several strings to its Items property:

procedure TRadioListBoxForm.FormCreate(Sender: TObject) ;
begin
   //or use Object Inspector to assign the
   //OnDrawItem event handler,
   //Style and ItemHeight properties...

   ListBox1.Style := lbOwnerDrawFixed;
   ListBox1.ItemHeight := 20;
   ListBox1.OnDrawItem := ListBox_DrawItem;
end;

procedure TRadioListBoxForm.ListBox_DrawItem(
   Control: TWinControl;
   Index: Integer;
   Rect: TRect;
   State: TOwnerDrawState) ;
const
   IsSelected : array[Boolean] of Integer = (DFCS_BUTTONRADIO, DFCS_BUTTONRADIO or DFCS_CHECKED) ;
var
   optionButtonRect: TRect;
   listBox : TListBox;
begin
   listBox := Control as TListBox;
   with listBox.Canvas do
   begin
     FillRect(rect) ;

     optionButtonRect.Left := rect.Left + 1;
     optionButtonRect.Right := Rect.Left + 13;
     optionButtonRect.Bottom := Rect.Bottom;
     optionButtonRect.Top := Rect.Top;

     DrawFrameControl(Handle, optionButtonRect, DFC_BUTTON, IsSelected[odSelected in State]) ;

     TextOut(15, rect.Top + 3, listBox.Items[Index]) ;
   end;
end;
Note: the Style property sets ListBox1 owner drawing to true. The OnDrawItem is used to draw a radio button for each of the items.

Delphi tips navigator:
» Create a Resizable Form with No Border
« Display "Bold" Items in the TTreeView

More Delphi Programming Quick Tips
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 Draw a Radio Button for a TListBox Item in Delphi

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

All rights reserved.