Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your first example is doing one level of recursion, so you're getting TextBoxes that are more than one control deep in the control tree. The second example only gets top-level TextBoxes (which you likely have few or none).</p> <p>The key here is that the <code>Controls</code> collection is not every control on the page - rather, it is only the <strong>immediate child controls</strong> of the current control (and a <code>Page</code> is a type of <code>Control</code>). <em>Those</em> controls may in turn have child controls of their own. To learn more about this, read about the <a href="http://aspalliance.com/943" rel="noreferrer">ASP.NET Control Tree here</a> and about <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx" rel="noreferrer">NamingContainers here</a>. To truly get every TextBox anywhere on the page, you need a recursive method, like this:</p> <pre><code>public static IEnumerable&lt;T&gt; FindControls&lt;T&gt;(this Control control, bool recurse) where T : Control { List&lt;T&gt; found = new List&lt;T&gt;(); Action&lt;Control&gt; search = null; search = ctrl =&gt; { foreach (Control child in ctrl.Controls) { if (typeof(T).IsAssignableFrom(child.GetType())) { found.Add((T)child); } if (recurse) { search(child); } } }; search(control); return found; } </code></pre> <p>Which is used as an <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx" rel="noreferrer">extension method</a>, like so:</p> <pre><code>var allTextBoxes = this.Page.FindControls&lt;TextBox&gt;(true); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload