Home > .net 3.5, c#, Microsoft, Visual Studio 2008 > Using the OfType Extension to Filter ControlCollections

Using the OfType Extension to Filter ControlCollections

May 12, 2008

There are a few different ways to iterate through the Control structure of an ASP.NET page.

You can simply find a control based on the associated ID.  Unfortunately, you can’t loop through this and it requires knowing the EXACT Id field for each control.

var ibc =
       myContainer.FindControl(“MyId”) as
              IndicatorBlockControl;

You can foreach through the ControlCollection and match to the type of each control.

foreach (Control control in myContainer.Controls)

{

       if (control.GetType() ==

               typeof(IndicatorBlockControl))

       {

                     // Logic here…

       }

}

Or, you can use one of the neat new built-in extension methods.

foreach (var indControl in

       myContainer.Controls.OfType<IndicatorBlockControl>())

{

       // Logic here.

}

One less iterator statement (at least that I have to code, I’m sure it’s the same in the IL) and a bit less headache.  Cool.

%d bloggers like this: