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

How to Access a TRadioButton from a TRadioGroup - Disable, Change Font, etc.

By , About.com Guide

Customizing TRadioButton from TRadioGroup

The TRadioGroup Delphi component represents a group of radio buttons that function together. To add radio buttons to a TRadioGroup, edit the Items property - each string in Items makes a radio button appear in the group box with the string as its caption.

Here's how to access a specific radio button either by Index or by Caption. When you "grab" the TRadioButton you can disable it, change its color, etc...

The two overloaded custom functions "RadioGroupButton" return a TRadioButton for a provided Index or Caption from a RadioGroup:

function RadioGroupButton(itemIndex : integer; radioGroup : TRadioGroup) : TRadioButton; overload;
begin
   if (itemIndex < 0) OR (itemIndex >= radioGroup.Items.Count) then
   begin
     result := nil;
     Exit;
   end;

   result := radioGroup.Controls[itemIndex] as TRadioButton;
end;

function RadioGroupButton(itemText : string; radioGroup : TRadioGroup) : TRadioButton; overload;
//returns only the first item with itemText Caption
var
   cnt : integer;
   buttonIndex : integer;
begin
   buttonIndex := -1;
   for cnt := 0 to -1 + radioGroup.Items.Count do
   begin
     if radioGroup.Items[cnt] = itemText then
     begin
       buttonIndex := cnt;
       break;
     end;
   end;

   result := RadioGroupButton(buttonIndex,radioGroup) ;
end;
Note: to access an item (TRadioButton) from the radio group, the Controls property is used. All radio buttons that share the same Parent (radioGroup) are available as part of the Controls property of that Parent.

And here's an example of usage:

var
   rb : TRadioButton;
begin
   //disable 6th item
   rb := RadioGroupButton(4,RadioGroup1) ;
   if rb <> nil then
     rb.Enabled := false;

   //Bold item
   rb := RadioGroupButton('Change Font,',RadioGroup1) ;
   if rb <> nil then
     rb.Font.Style := rb.Font.Style + [fsBold];

   //Change back color
   rb := RadioGroupButton(0,RadioGroup1) ;
   if rb <> nil then
     rb.Color := clRed;

   //Change font color
   rb := RadioGroupButton(2,RadioGroup1) ;
   if rb <> nil then
     rb.Font.Color := clGreen;
end;

Delphi tips navigator:
» How to Display "Bold" Items in the TTreeView component
« How to Jump to the Last Item in the TListBox

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TRadioButton, TCheckBox
  6. How to Access a TRadioButton from a TRadioGroup - Disable, Change Font, etc.

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

All rights reserved.