Using a radio button group in an application
Sometimes only one of several options may be chosen: one correct answer in a test question, one way of aligning text. For this a RadioGroup (Standard tab) is used: choosing one automatically cancels the others. The options are in the Items property, each on a new line (double-click Items in the Object Inspector). ItemIndex holds the number of the chosen option; counting starts at 0, so the second option in the list has ItemIndex 1, and if nothing is chosen it is –1. Columns sets in how many columns the options are arranged: each column holds at most (number of options + number of columns – 1) div number of columns buttons, so the last column can stay empty. To check whether a choice exists, the code uses if RadioGroup1.ItemIndex >= 0 then …
| Choice | ItemIndex | Items[ItemIndex] |
|---|---|---|
| Futbol | 0 | Futbol |
| Shaxmat | 1 | Shaxmat |
| Suzish | 2 | Suzish |
| Voleybol | 3 | Voleybol |
| nothing | –1 | none |
The name “radio button” comes from old car radios, where pressing one station button made the previous one pop out. A group that works like this is handy for choosing a time for a trial session: only one of “morning” or “afternoon” can be chosen. If you choose another, the first is cancelled.
Form designers, developers of test apps and kiosk makers use this kind of choice wherever only one answer is allowed.
Label 3 circles on paper with different options, put a dot in one, then choose another and rub out the first dot: only one dot should ever remain.
1procedure TForm1.Button1Click(Sender: TObject); 2begin 3 if RadioGroup1.ItemIndex >= 0 then 4 Label1.Caption := 'Tanlandi: ' + RadioGroup1.Items[RadioGroup1.ItemIndex] 5 else 6 Label1.Caption := 'Hech narsa tanlanmagan'; 7end;
“One vote”: the class creates a survey application with a RadioGroup; 10 “votes” are entered and the totals per option are compared with the value counted by hand.