How can I give a radio button a value and determine the selected radio button without using a GroupBox

19,199

Solution 1

If you want to assign an arbitrary value to the control, use its Tag property:

radColor1.Tag = 5;

But why can't you simply use the Checked property?

if (radColor1.Checked)
    //do something
if (radColor2.Checked)
    //do something else
//...however many more you need to check

EDIT: iteration...

foreach (Control c in this.Controls)
{
    if (c is RadioButton)
    {
        if (((RadioButton)c).Checked)
        //do something
    }
}

Solution 2

put these radio btns in a stackPanel and iterate to check If Checked & than use tag property to store the values of each radio button

foreach(var child in stack.Children)
{
    if((child as RadioButton).Checked == true)
    var value = (child as RadioButton).tag;
}

Solution 3

RadioButton radSelected = (from RadioButton rb in this.Controls
                          where rb.Checked 
                          select rb).SingleOrDefault();
Share:
19,199
Popokoko
Author by

Popokoko

Updated on June 09, 2022

Comments

  • Popokoko
    Popokoko almost 2 years

    I have a form with few radio buttons that suppose to represent different integer values.

    1) Is there a built-in way to put a value "behind" a radio button? an example:

    RadioButton rad = new RadioButton();
    rad.Value = 5; // This is what im trying to achieve.
    

    2) I have few RadioButtons that are logically related to each other and i want to know which one was selected (without putting them inside a GroupBox control) and get the selected value for that RadioButton. note: I would like to "Iterate" these 3 controls and get the selected one instead of doing 3 IF statements. an example:

    RadioButton radColor1 = new RadioButton();
    RadioButton radColor2 = new RadioButton();
    RadioButton radColor3 = new RadioButton();
    
    // ...
    
    RadioButton radSelected = ?? // Get selected Radio Button from the 3 above.
    //here i can get to radSelected.Value