Advertisement
sirjordan

GetControls & GetControlsRecursive

May 27th, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. public static class ControlExtender
  2.     {
  3.         /// <summary>
  4.         /// Recursively finds controls of Type T, started from the root.
  5.         /// </summary>
  6.         /// <typeparam name="T">Type of the returned controls</typeparam>
  7.         /// <param name="root">Root control to starts from</param>
  8.         public static IEnumerable<T> GetControlsRecursive<T>(this Control root) where T : Control
  9.         {
  10.             foreach (T control in root.Controls.OfType<T>())
  11.             {
  12.                 yield return (T)control;
  13.  
  14.                 if (control.HasControls())
  15.                 {
  16.                     foreach (T childControl in GetControls<T>(control))
  17.                     {
  18.                         yield return childControl;
  19.                     }
  20.                 }
  21.             }
  22.         }
  23.  
  24.         /// <summary>
  25.         /// Finds controls of Type T.
  26.         /// </summary>
  27.         /// <typeparam name="T">Type of the returned controls</typeparam>
  28.         /// <param name="controlToSearch">Control to search</param>
  29.         public static IEnumerable<T> GetControls<T>(this Control controlToSearch) where T : Control
  30.         {
  31.             foreach (T child in controlToSearch.Controls.OfType<T>())
  32.             {
  33.                 yield return (T)child;
  34.             }
  35.         }
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement