Search code examples
c#winformsuser-controls

Issue while iterating through User Controls in a Windows Form


I am facing an issue while running through all the User Controls in my Windows form.

I am creating a Windows Form that has the following features:

  1. The Main form has 3 User Controls embedded in it
  2. The Main form also has a combo box. Selecting a particular value in the Combo box will bring the corresponding User Control to the front.
  3. Each User Control has two Check boxes as well as two Combo boxes.
  4. The User can summon each User Control through the Main Form's combo box and check the check boxes and/or modify the combo boxes inside each User Control
  5. Once this is done, there is a button, which on being pressed, executes the following code. This code is supposed to check which check boxes have been checked from every User Control, and execute some functionality :
private void button1_Click(object sender, EventArgs e)
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                {
                    foreach (Control ctl in c.Controls)
                    {

                        if (ctl is CheckBox && (ctl as CheckBox).Checked)
                        {
                            Indicator.Text = "It's in";
                        }
                    }
                }
            }
            //Some other code after this
         }

Here, I have included a Text Box called "Indicator" that shows whether the compiler has entered a particular "for" loop or "if" block. And I'm observing that the innermost "if" alone is not getting executed.

Could someone point out why exactly this is happening?


Solution

  • Thanks to everyone for the answers. As it happens, the issue was hiding in plain sight, right under my nose. In each of the User Controls, I had placed the Checkboxes and Combo Boxes inside a Group Box. It completely slipped my mind, so much so that I didn't even mention them in my question.

    Thus, as @Caius had suggested in the comments, the code wasn't functioning because I had not addressed the Group Box Container holding these Controls. Once I removed the Group Boxes (used only for aesthetic purpose), the code started functioning properly.