Your first example runs one recursion level, so you get TextBoxes that contain more than one control in the control tree. In the second example, only top-level text fields (which are probably few or not) are received.
The key point here is that the Controls collection is not every control on the page โ rather, it is only the immediate child controls of the current control (and Page is the type of Control ). These controls, in turn, may have their own control elements. To learn more about this, read about the ASP.NET Management Tree here and NamingContainers here . To really get every text block anywhere on the page, you need a recursive method, for example:
public static IEnumerable<T> FindControls<T>(this Control control, bool recurse) where T : Control { List<T> found = new List<T>(); Action<Control> search = null; search = ctrl => { foreach (Control child in ctrl.Controls) { if (typeof(T).IsAssignableFrom(child.GetType())) { found.Add((T)child); } if (recurse) { search(child); } } }; search(control); return found; }
Used as an extension method , for example:
var allTextBoxes = this.Page.FindControls<TextBox>(true);
Rex m
source share