Which radio button is selected in a TRadioGroup?

A TRadioButton has the Checked property. But A TRadioGroup has the ItemIndex property.

The items in a TRadioGroup are stored using a TStrings. So you can associate an object to each option and you can cast an integer to a TObject to be stored.

Example:

// fill the radiogroup
radiogroup.Items.AddObject('Fit 2xWidth', TObject(0));
radiogroup.Items.AddObject('Fit 2xHeight', TObject(1));
radiogroup.Items.AddObject('Fit Width', TObject(2));
radiogroup.Items.AddObject('Fit Height', TObject(3));
radiogroup.ItemIndex := 0;

To read the current setting:

value := radiogroup.ItemIndex;

Or to get the associated integer:

index := radiogroup.ItemIndex;
Assert(index>=0); // Sanity check
value := Integer(radiogroup.Items.Objects[index]);

In your case, the values are 0 to 3 so you can use the ItemIndex.

As a note, if is not a function. A function is a piece of code that returns a value based on the input parameters. If is a statement, which is a command that can be executed. The if statement is special because it enables you to execute a different statement based on the if condition.


Just a little TIP: Setting .ItemIndex does not send keyboard focus to the radio item, i know how to fix it, read ahead.

Instead of selecting by code a Radio in a RadioGroup by setting .ItemIndex it is much better to do it by sending focus to the radio item; just to be very clear: i mean sending focus just to the radio item, not the whole radio group.

Instead of: radiogroup.itemindex:=TheIndex;

Do it as this: TRadioButton(radiogroup.Controls[TheIndex]).SetFocus;

It will make the radio item to be selected and send the keyboard focus to it, so it will display the dotted rectangle arroud it, just as if the user had clicked on it.

Note1: To see it in action use keyboard cursor keys and compare behavor of just setting .ItemIndex and sending focus to radio item.

Note2: If you use TRadioButton(radiogroup.Controls[TheIndex]).SetFocus; then there is no no need to set .ItemIndex at all, it will also be done.

Hope that helps someone having the same problem as me, when need to set it by code, for example to avoid circular keyboard behavor, for example for making it to stay on last radio item when last radio item is selected and keyboard right cursor is pressed, same for first.