Search code examples
c#asp.netreflectionweb-controls

looping through Page Controls - using same logic for multiple control types


I'm looping through the page controls like so

      foreach (Control ctrl in control.Controls)
      {
          if (ctrl is System.Web.UI.WebControls.TextBox || ctrl is System.Web.UI.WebControls.Label)
          {
          }
      }

I want to be able to declare a variable inside this if statements that is the same type as 'ctrl' in the foreach so that I can inspect the properties of the control and perform some manipulations that way. I don't want to duplicate code, for example, if 'ctrl' is a textbox, or label, because I would be executing the same code for those 2 web control types.

Any help leading me in the right direction is greatly appreciated!

Thanks


Solution

  • Try using the ITextControl interface:

    foreach (Control ctrl in control.Controls)
    {
        ITextControl text = ctrl as ITextControl;
        if (text != null)
        {
            // now you can use the "Text" property in here,
            // regardless of the type of the control.
        }
    }
    

    You can also use the OfType extension method here to clean this up a bit:

    foreach (ITextControl text in control.Controls.OfType<ITextControl>())
    {
        // now you can use the "Text" property in here,
        // regardless of the type of the control.
    }