I have the following method to return a List of WebControl
s 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.
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>());
}