views:

47

answers:

1

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

A: 

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.
}
Andrew Hare
I want to access properties of 'ctrl' such as CssClass, and casting to ITextControl does not give the accomodations (that I saw) for me to do that. Thanks for the quick response Andrew!
TheGeekYouNeed
Try using `WebControl` then instead of `ITextControl` that will give you access to `CssClass` at least. The trick is to find the lowest common denominator between your types.
Andrew Hare
ok - that is the direction I was headed myself, too - thanks for confirming my thought :)
TheGeekYouNeed