-1

I want to find all controls in my form that implement a certain interface (let's say ITestInterface). I have tried this:

this.Controls.OfType<ITestInterface>();

but it goe's only one level deep (despite what is written in MSDN - @dasblinkenlight), so if for example, I have a panel in the form and an ITestInterface control inside the panel, it will not find it.

How to do that?


Edit: As @HansPassant wrote in a comment, I could hard-code my panels name, however, I need a general solution, and not a specific solution to a particular form.

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82

1 Answers1

2

You have to use recursion and step through the Controls property of your controls:

private IEnumerable<T> GetAllOfType<T>(Control rootControl)
{
    return rootControl.Controls.OfType<T>().
           Concat(rootControl.Controls.OfType<Control>().SelectMany(GetAllOfType<T>));

}

You can use this like:

var allOfTestInterface = GetAllOfType<ITestInterface(this);

It takes all controls with that interface that are directly contained by the root control (with your OfType<>() call) and then calls the method again for all controls contained by that control, thus recursing through all containers. SelectMany flattens this nested lists into one list.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • 1
    @dasblinkenlight yes, the wording is rather vague, they don't really say nested controls are included, they say you can use `Controls` to "iterate through all controls of a form, including nested controls", that's not 100% the same ;) – René Vogt Dec 18 '17 at 15:00