Search code examples
c#user-controlscontrols

Find nested Control inside a user control


Hi I have a panel that contains a usercontrol that contains a repeater that can have one or more checkboxes.

I want to get status of all check boxes that currently are in the panel.

My current code is

bool isChecked = false;

        foreach (Control control in pnlLoanProcess.Controls)
        {
            if (control is BookLoanActions)
            {
                BookLoanActions uc = (BookLoanActions)control;

                foreach (Control c in uc.Controls)
                {

                    if (c.GetType() == typeof(Repeater))
                    {
                        Repeater rptr = (Repeater)c;
                        foreach (Control c1 in rptr.Controls)
                        {
                            if (c1.GetType() == typeof(CheckBox))
                            {
                                CheckBox chkBox = (CheckBox)c1;
                                if (chkBox.Checked)
                                    isChecked = true;
                            }
                        }
                    }
                }
            }
        }

Is there a shorter/better way to do this?


Solution

  • Sure, there is...

    foreach (var bla in pnlLoanProcess.Controls.OfType<BookLoanActions>())
    {
        foreach (var rptr in bla.Controls.OfType<Repeater>())
        {
            isChecked = rtpr.Controls.OfType<CheckBox>().Any(c => c.IsChecked));
        }
    }
    

    You could probably even shorten that up with some clever LINQ.