Which radio button is selected in a TRadioGroup?

Nathan Campos picture Nathan Campos · Dec 31, 2009 · Viewed 36.9k times · Source

As you can see in my question history, I'm developing a eBook manager, that will be open-source and I will release it in about 10 days, but I have a TRadioGroup, as you can see:
TRadioGroup Used On My Form http://img85.imageshack.us/img85/1830/radiogroup.png

And I want to store somethings in a variable(that needs to be a Integer) that will be "linked" with this TRadioGroup.

I need to do a if function like this:

Caption Of The TRadioButton -> Number that will need to be stored in the variable

Fit 2xWidth - Default -> 0
Fit 2xHeight -> 1
Fit Width -> 2
Fit Height -> 3

But I just used a TRadioGroup and a TRadioButton one time, different than in C# that I've used more than 20 times. Then I want to know what I need to put on the if function, because what it will do I already know how to do:

var
  num: Integer;

begin
  if(TRadioButton1 checked?)
  begin
    num := 0;
  end;
end.

What I need to put inside the brackets of the if function?

PS: I'm going to put the credits on the program for the people that helped me in this little project.

Answer

Toon Krijthe picture Toon Krijthe · Dec 31, 2009

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.