Sumedh Meshram

A Personal Blog


Finding all controls in an ASP.NET Page

This can be done through enumerating all the controls in the control hierarchy:

Add a method in a common class


/// <summary>
/// Find the Controls inside a Page
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public static IEnumerable<Control> EnumerateControlsRecursive(Control parent)
     foreach (Control child in parent.Controls)
            yield return child;
            foreach (Control descendant in EnumerateControlsRecursive(child))
               yield return descendant;


Implement this method like this on the PreRender event of a page :


 protected override void OnPreRender(EventArgs e)
      foreach (var control in RecursiveHelper.EnumerateControlsRecursive(this))
        if (control is TextBox)
           SetTextBoxStyle(control as TextBox);

        if (control is RegularExpressionValidator)
           SetTextBoxEnterValidation(control as RegularExpressionValidator);


Then add your method seperately for assigning the common attributes to each control.


 private static void SetTextBoxStyle(TextBox textBox)
       textBox.CssClass = "emptyMessageStyle";



Hope this will help.


Add comment

  Country flag

  • Comment
  • Preview