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

3

5

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
Slab answered 6/6, 2013 at 13:3 Comment(1)
Your question contains two different topics. Please post two seperate questions the next time.Interact
S
6

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
    }
}
Sod answered 6/6, 2013 at 13:6 Comment(3)
I would like to "Iterate" these 3 controls and get the selected one instead of doing 3 IF statements.Slab
Regarding the (1)'s solution: the Tag property definitely helps, i wasn't sure about if should i use it or not. (2): The only problem is that u actually iterating the entire radio buttons on the form and i want to "iterate" certain number of them without putting them inside a groupbox or something like that. maybe i should use a panel for them?Slab
You'll need some way to distinguish them. A containing control of some kind works. Naming them a certain way works. Flagging each using Tag works. But if it's 3/10 radio buttons, you need to spot them somehow.Sod
P
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;
}
Pelag answered 6/6, 2013 at 13:11 Comment(0)
C
2
RadioButton radSelected = (from RadioButton rb in this.Controls
                          where rb.Checked 
                          select rb).SingleOrDefault();
Commentary answered 6/6, 2013 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.