Iterating over ControlCollection returns 0 results

76 Views Asked by At

I have the following method to return a List of WebControls in my helper class:

public static List<T> GetControls<T>(ControlCollection cCol) where T : WebControl
{
    List<T> results = new List<T>();
    foreach (Control control in cCol)
    {
        if (control is T)
            results.Add((T)control);

        if (control.HasControls())
            GetControls<T>(control.Controls);
    }
    return results;
}

On my aspx page there is one UpdatePanel containing 3 asp:CheckBoxList controls. To populate my List I use the above described method, where CheckBoxPanel is the UpdatePanel containing my controls.

List<CheckBoxList> cbCol = Helper.GetControls<CheckBoxList>(CheckBoxPanel.Controls);

This line returns 0 results, which indicates, that my method GetControls<T>(ControlCollection cCol) is wrong.

Please help my find the flaw in my train of thoughts.

2

There are 2 best solutions below

0
On BEST ANSWER

Your results is a local variable. So for every recursive call you add some controls and forget it.

It should be passed as a parameter in all the recursive calls, only then controls will be populated in same list.

Not tested, but the following code should work:

private static List<T> GetControls<T>(ControlCollection cCol, List<T> results) where T : WebControl
{
    foreach (Control control in cCol)
    {
        if (control is T)
            results.Add((T)control);
        if (control.HasControls())
            GetControls<T>(control.Controls, results);
    }

    return results;
}

public static List<T> GetControls<T>(ControlCollection cCol) where T : WebControl
{
    return GetControls(cCol, new List<T>());
}
0
On

You can use Snram solution or just simply:

if (control.HasControls())
            results.AddRange(GetControls<T>(control.Controls));

The only thing you need is to add recrusive call output to the result.

Snram solution might be quite better because you do not create list instance every recrusive call (in my solution GC have to take care of unused list and remove it from memory).