Mega Code Archive

 
Categories / Delphi / VCL
 

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

Title: How to Access a TRadioButton from a TRadioGroup - Disable, Change Font, etc. 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 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; ControlCount = 0 ?!? If you try to call the above code in the, for example, Form.OnCreate event handler, you might receive an access violation with "radioGroup.Controls[itemIndex]". The Controls property will be empty even if you have specified some items at design time. The issue is with how VCL creates window handles - on the "just when needed" (lazy-load) bases. This basically means that Controls property will be empty until the radiogroup is displayed, unless your code requests the handle explicitly. The solution is to call "radioGroup.HandleNeeded" before you access radioGroup's Controls property.