SharePoint: How to find all controls of a certain type
A small, but useful method to find recursively all controls of a certain type:
public static List<T> FindControlRecursiveByType<T>(Control root) where T : Control { List<T> res = new List<T>(); if (root != null) { Stack<Control> tmpStack = new Stack<Control>(); tmpStack.Push(root); while (tmpStack.Count > 0) { Control ctrl = tmpStack.Pop(); if (ctrl is T) res.Add(ctrl as T); foreach (Control childCtrl in ctrl.Controls) tmpStack.Push(childCtrl); } } return res; }
The sample usage is below:
// return all save buttons on the page List<SaveButton> saveButtons = FindControlRecursiveByType<SaveButton>(Page);