65.9K
CodeProject is changing. Read more.
Home

Findcontrol using a non recursive approach

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Nov 1, 2011

CPOL
viewsIcon

15346

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:

public static List<control> FindControlsWidthFirst( Control controlTop )
{
    List list = new List();
    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 list = new List();
    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;
}