Organizational Research By

Surprising Reserch Topic

find all child controls of specific type using enumerable oftypet or linq


find all child controls of specific type using enumerable oftypet or linq  using -'c#,.net,asp.net,linq,findcontrol'

Existed MyControl1.Controls.OfType<RadioButton>() searches only thru initial collection and do not enters to children.

Is it possible to find all child controls of specific type using Enumerable.OfType<T>() or LINQ without writing own recursive method? Like this.
    

asked Sep 29, 2015 by ajit.chavhan
0 votes
10 views



Related Hot Questions

3 Answers

0 votes

I use an extension method to flatten control hierarchy and then apply filters, so that's using own recursive method.

The method looks like this

public static IEnumerable FlattenChildren(this Control control)
{
  var children = control.Controls.Cast();
  return children.SelectMany(c => FlattenChildren(c)).Concat(children);
}
answered Sep 29, 2015 by ukohale
0 votes

I use this generic recursive method:

The assumption of this method is that if the control is T than the method does not look in its children. If you need also to look to its children you can easily change it accordingly.

public static IList GetAllControlsRecusrvive(Control control) where T :Control 
{
    var rtn = new List();
    foreach (Control item in control.Controls)
    {
        var ctr = item as T;
        if (ctr!=null)
        {
            rtn.Add(ctr);
        }
        else
        {
            rtn.AddRange(GetAllControlsRecusrvive(item));
        }

    }
    return rtn;
}
answered Sep 29, 2015 by santosh soni
0 votes

Thanks to the above answer plus the comments, I made it work for me like this:

//Returns all controls in all levels:
public static IEnumerable AllControls( this Control theStartControl )
{
   var controlsInThisLevel = theStartControl.Controls.Cast();
   return controlsInThisLevel.SelectMany( AllControls ).Concat( controlsInThisLevel );
}

//Returns all controls of a certain type in all levels:
public static IEnumerable AllControls( this Control theStartControl ) where TheControlType : Control
{
   var controlsInThisLevel = theStartControl.Controls.Cast();
   return controlsInThisLevel.SelectMany( AllControls ).Concat( controlsInThisLevel.OfType() );
}

//(Another way) Returns all controls of a certain type in all levels, integrity derivation:
public static IEnumerable AllControlsOfType( this Control theStartControl ) where TheControlType : Control
{
   return theStartControl.AllControls().OfType();
}
answered Sep 29, 2015 by deepak

...