Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IEnumerable

Findcontrol using a non recursive approach

5.00/5 (3 votes)
25 Nov 2011CPOL 15.3K  
Ha! I get it....I am actually using an adaptation of this technique in production code.But the adapted code required a dept-first search and this original pattern is width-first.Which brings us these new and improved versions:public static List FindControlsWidthFirst( Control...

Ha! I get it....



I am actually using an adaptation of this technique in production code.
But the adapted code required a dept-first search and this original pattern is width-first.
Which brings us these new and improved versions:


C#
public static List<control> FindControlsWidthFirst( Control controlTop )
{
    List<control> list = new List<control>();
    list.Add(controlTop); 
    //NOTE: we are not using a foreach, 
    //      which means that as long as the current parent has children,
    //      list.Count increases... which means we will automatically 
    //      Get a next itteration because 'i' is still < than the count.
    for (int i = 0; i < list.Count; ++i)
    {
        list.AddRange(list[i].Controls);
    } 
    return list;
}
public static List<control> FindControlsDepthFirst( Control controlTop )
{
    List<control> list = new List<control>();
    list.Add(controlTop); 
    //NOTE: we are not using a foreach, 
    //      which means that as long as the current parent has children,
    //      list.Count increases... which means we will automatically 
    //      Get a next itteration because 'i' is still < than the count.
    for (int i = 0; i < list.Count; ++i)
    {
        // insert into the position for the next itteration:
        list.InsertRange(i + 1, list[i].Controls);
    } 
    return list;
}
</control></control></control></control>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)