1. Computing & Technology

Discuss in my forum

TListBox with Radio Buttons

By , About.com Guide

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

©2012 About.com. All rights reserved.

A part of The New York Times Company.