I see a lot of methods on the web which allow you to find controls on your web page recursive by id and name, but never by type, so I decided to post mine. The first method returns a list of all controls which match the type. The second method only returns the first one which is of the given type.
Enjoy
using System.Collections.Generic;
namespace VNX.Helpers
{
public class ControlHelper
{
public static List<T> FindControlsOfTypeRecursive<T>(System.Web.UI.ControlCollection controls) where T : class
{
List<T> found = new List<T>();
if (controls != null && controls.Count > 0)
{
for (int i = 0; i < controls.Count; i++)
{
if (controls[i] is T)
{
found.Add(controls[i] as T);
break;
}
else
found.AddRange(FindControlsOfTypeRecursive<T>(controls[i].Controls));
}
}
return found;
}
public static T FindFirstControlOfTypeRecursive<T>(System.Web.UI.ControlCollection controls) where T : class
{
T found = default(T);
if (controls != null && controls.Count > 0)
{
for (int i = 0; i < controls.Count; i++)
{
if (controls[i] is T)
{
found = controls[i] as T;
break;
}
else
{
found = FindFirstControlOfTypeRecursive<T>(controls[i].Controls);
if (found != default(T))
{
break;
}
}
}
}
return found;
}
}
}