C# Windows Form - loop through all controls in controls collection for the form

I am attempting to create a UserControl for a Windows Form in order to accomplish the following:

-The design surface of the user control only has a checkbox control on it.
-In the code-behind I added an Interface:

 public partial class CodeGenCheckBox : UserControl, ICodeGenCheckBox

The interface is functioning as a sort of "tag" for the control, so that during run time type identification I can gather ALL the checkbox controls of type ICodeGenCheckBox into a List<  >  of type ICodeGenCheckBox, then loop through that list and do work.

Does the above approach sound workable?

Assuming for the moment that it is, what I am asking for is a method that I can call recursively that will iterate through ALL the controls and sub controls and sub sub controls (as deep as they are nested) on the form and in that recursive method call I want to add some logic that essentially says:  "if the control you are looking at is of type ICodeGenCheckBox, then add the control to the List<ICodeGenCheckBox>"

I know I've asked a similar question before, but I can't find it in my knowledge base (yet).  If I find it I'll come back here and post.

Solution code needs to be in C# for points on this question.
LVL 5
Tom KnowltonWeb developerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
List<ICodeGenCheckBox> l = new List<ICodeGenCheckBox>();

// start with the top control.
getControls(this.Form);

//the recursive function.

private void getControls(control c)
{
   if (c.getType()  == typeof(ICodeGenCheckBox))
                  l.Add((ICodeGenCheckBox)c);

   foreach(Control ctrl in c.Controls)
            getControls(ctrl);
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Tom KnowltonWeb developerAuthor Commented:
Is the call:

 getControls(this.Form);

or

 getControls(this);

???

this.Form   does not appear to be available...
0
Kyle AbrahamsSenior .Net DeveloperCommented:
whatever your top control is where you want to search down from.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Jacques Bourgeois (James Burger)PresidentCommented:
Kyle code is sound, but you do not need an interface to do that. Your UserControl can already be identified by it's type:

public partial class CodeGenCheckBox : UserControl

List<CodeGenCheckBox> l = new List<CodeGenCheckBox>();

// start with the top control.
getControls(this.Form);

//the recursive function.

private void getControls(control c)
{
   if (c.getType()  == typeof(CodeGenCheckBox))
                  l.Add((CodeGenCheckBox)c);

   foreach(Control ctrl in c.Controls)
            getControls(ctrl);
}

The Interface adds nothing except a little more work for the compiler, and possibly some kind of puzzlement for programmers who see it.
0
Tom KnowltonWeb developerAuthor Commented:
The Interface adds nothing except a little more work for the compiler, and possibly some kind of puzzlement for programmers who see it.

Yep, you're right, I don't need it.

Here is my current (final?) version:

 private void buttonGenerateCodeBasedOnSelections_Click(object sender, EventArgs e)
        {   
            textBoxResults.Text += "";

            getControls(this);

            foreach (DevHelper.CodeGenCheckBox cgcb in _CodeGenCBList)
            {
                CodeGenTypes cg = cgcb.CGType;

                switch(cg)
                {
                    case CodeGenTypes.MemberVariablesPrivate:
                        textBoxResults.Text += _CG.GeneratePrivateMemVars();
                        break;
                    case CodeGenTypes.Accessors:
                        textBoxResults.Text += _CG.GenerateAccessors();
                        break;
                    default:
                        textBoxResults.Text += "";
                        break;
                }               
            }
        }

        private void getControls(System.Windows.Forms.Control c)
        {
            if (c.GetType().ToString().Contains("CodeGenCheckBox"))
            {
               
                if (((CodeGenCheckBox)c).Checked)
                {
                    _CodeGenCBList.Add((CodeGenCheckBox)c);
                }               
            }

            foreach (Control ctrl in c.Controls)
            {
                getControls(ctrl);
            }
        }

Open in new window

0
Tom KnowltonWeb developerAuthor Commented:
NOTE:

Never at any time did I see this.Form as an option during Intellisense code completion.

But just passing "this" into the recursive method seems to work fine.
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
That's because the way you originally worded the problem, it sounded like you were running the code from within the UserControl itself.

It should actually be the .ParentForm() property:
https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Windows.Forms.ContainerControl.ParentForm);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true

If you're running from the Form itself then you don't need that.
0
Tom KnowltonWeb developerAuthor Commented:
That's because the way you originally worded the problem, it sounded like you were running the code from within the UserControl itself.

Oh, okay.  Thanks for the clarification!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.