I have a situation in a WebForm where I need to recurse throguh the control tree to find all controls that implement a given interface.
How would I do this?
I have tried writing an extension method like this
public static class ControlExtensions
{
public static List<T> FindControlsByInterface<T>(this Control control)
{
List<T> retval = new List<T>();
if (control.GetType() == typeof(T))
retval.Add((T)control);
foreach (Control c in control.Controls)
{
retval.AddRange(c.FindControlsByInterface<T>());
}
return retval;
}
}
But it does not like the cast to T on line 7. I also thought about trying the as operator but that doesn't work with interfaces.
I saw Scott Hanselmans disucssion but could not glean anything useful from it.
Can anyone give me any pointers. Thanks.
Greg