Flattening System.Web.UI ControlCollection

Hi,

 

Sometimes one may need to get a list of child controls inside specific container and don't care about the underlying hierarchy.

 

The result is beautifully achieved using this extension method:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

 

 public static class ControlCollectionExtensionMethods
    {
        public static IEnumerable<Control> FlattenedList(this ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                  // return parent control
                   yield return ctrl;
           

                  // and dive into child collection
                   foreach (Control child in ctrl.Controls.FlattenedList())
                         yield return child;
            }
        }
    }

 

P.S.: don't forget about namespaces when using it in your code, if above class is wrapped into namespace, for example: Sample, the source code file with calling code must explicitly reference it: using Sample;

6 Comments

  • Won't SelectMany with LINQ do that for you?

  • It might not be appropriate to use it for such task

  • Genius. Saved my bacon on this one. I was trying to do all sorts of nonsense with controlcollection.add that just wasn't behaving how I'd expect, but your solution saved the day. Just wanted to say thanks!

  • well, i do believe in astrology and horoscope is that the first part of that the magazine that i
    always check~

  • His or her shape of unrealistic tats were initially threatening.
    Lindsay utilized gun first basic, whereas this
    girl snuck outside by printer ink dog pen. I used
    absolutely sure that the all truly on that the shade, with that the tattoo
    can be taken out of the body shape. make an own temporary tattoo

  • A whole lot of thanks for spending some time to talk about this, I feel strongly about it and love learning
    more about this topic. If at all, while you gain expertise,
    can you mind updating your website with extra information?

    It’s very great for me.

Comments have been disabled for this content.