Search code examples
c#winformsradio-buttongroupbox

How do I iterate through a Groupbox of multiple types and still read a property? (C# Windows Forms)


I'm trying to iterate through a GroupBox of GroupBoxes of RadioButtons, but I'm getting stuck because the GroupBoxes also contain other nodes such as Labels and TextBoxes. For better clarification, the tree of nodes is:

Groupbox
\/
GroupBox(es) + TextBox + Label
\/
RadioButton(s) + TextBox

My goal is to iterate through all possible RadioButtons, finding which in each section is checked, if any (or in other words, has the property (radiobuttonname).Checked == True) I can't seem to do this, though, as there's a problem with every solution I've come up with.

The Code:

int i = 0;
RadioButton[] currentData = [null, null, null, null, null, null, null, null];
        
foreach(Control group in check.Controls)
{
    if (group is GroupBox)
    {
        foreach(Control rb in group.Controls)
        {
            if (rb is RadioButton) //All RadioButtons are correctly recognized (confirmed by print test)
            {
                if ((RadioButton) rb.Checked){ //Cannot Resolve Symbol "Checked"
                    currentData[i] = ((RadioButton) rb);
                    break;
                }
            }
        }
                
        i++;
    }
}

return currentData;

The above should first enter the primary GroupBox, then enter each secondary GroupBox, then iterate through each RadioButton and add the checked RadioButton to the to-be-returned array (leaving null if there is none).

Solutions/Issues: -I could run these as foreach(RadioButton rb in group.Controls)? But if I do, the program fails because I'm casting a TextBox as a Radiobutton -I could run foreach as a for loop instead, finding a way to bypass the issue? But the number of nodes in each GroupBox varies, and I don't believe I can iterate through one like an array -I could cast the Controls (that I know are RadioButtons) as RadioButtons, as seen above? But as long at they become Controls first, they seem to lose the ability to access the .Checked property -I could remove all non-RadioButtons from the GroupBoxes? But that would defeat the point of the application I'm making...

Any help would be appreciated. I've been stuck on this for days, and would like to move on.


Solution

  • As much as you call something something specific, does not make it so. Your rb variable is a Control Type. However, if you where to cast it to a RadioButton and say that it should act like it and not just have the name thereoff, then it would act as you would like it to. There is more than one way to do it, but you could do something like this:

    foreach(Control cntrl in group.Controls)
        {
            if (cntrl is RadioButton rb) //All RadioButtons are correctly recognized (confirmed by print test)
            {
                //do stuff with you RadioButton rb
            }
        }