Sunday, April 19, 2015

ASP.Net C# Extension Method to Get All Controls (Recursive)

Here is another extension method I use frequently to recursively find all controls (optionally of a certain type) on the page or within a parent.

Code:
     public static IEnumerable<Control> GetAllControls(this Control Parent, System.Type Type = null)  
     {  
       if (Parent == null)  
       {  
         yield break;  
       }  
   
       if (Type == null || Parent.GetType().Equals(Type))  
       {  
         yield return Parent;  
       }  
   
       foreach (Control Control in Parent.Controls)  
       {  
         foreach (Control x in Control.GetAllControls(Type))  
         {  
           yield return x;  
         }  
       }  
     }  

Example usage:
 List<Control> PageControls = Page.GetAllControls().ToList();  
 IEnumerable<Control> DropDownLists = Page.GetAllControls(typeof(DropDownList));  

2 comments:

  1. It would be better to use LINQ to limit the types: Page.GetAllControls().OfType(); It requires just a couple of extra characters, and will be more recognizable.

    ReplyDelete
  2. I agree, thanks for pointing that out.

    ReplyDelete