4

Iam using windows forms. How can I query all child controls of a Form recursively which have a certain type?

In SQL you would use a selfjoin to perform this.

var result = 
  from this 
  join this ????
  where ctrl is TextBox || ctrl is Checkbox
  select ctrl;

Can I also do this in LINQ?

EDIT:

LINQ supports joins. Why can't I use some kind of selfjoin?

codymanix
  • 28,510
  • 21
  • 92
  • 151

2 Answers2

4

Something like this should work (not perfect code by any means...just meant to get the idea across):

public IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
{
    List<Control> controls = new List<Control>();

    foreach(Control child in parent.Controls)
    {
        controls.AddRange(GetSelfAndChildrenRecursive(child));
    }

    controls.Add(parent);

    return controls;
}

var result = GetSelfAndChildrenRecursive(topLevelControl)
    .Where(c => c is TextBox || c is Checkbox);
EKOlog
  • 410
  • 7
  • 19
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • The signature returns IEnumerable but in actuality you're returning a list. Consider yield return for deferment. – as9876 Jul 01 '16 at 00:37
-1

may be this will help you...

How can I get all controls from a Form Including controls in any container?

once you have the list you can query'em

Community
  • 1
  • 1
Luiscencio
  • 3,855
  • 13
  • 43
  • 74