How to set focus to a web control in ASP.NET
<p>Question:  What is the best way to set focus to a web control in ASP .NET.</p>

<p>I can do it, but it's ugly.  I have a web control wrapped in a web control hosted on a web page.  So, if you do a view | source on the page the id is something like WrapperControl_Control_TextBox.</p>

<p>I've tried the "tried and true" Javascript methods of grabbing the element and setting it's focus:  document.getElementByID( "WrapperControl_Control_TextBox" ).focus(); and it didn't work.  I'm not sure why.</p>

<p>I know I could possibly do:
document.getElementById( "&lt;%= TextBox.ClientID %>" ).focus(); too, I think.  This won't work because of another totally separate error based on the fact you can't dynamically add controls to a header if there is a "&lt;% %>" in the page.  GAH.</p>

<p>In the "bottom-most" control, I've tried setting the focus (TextBox.Focus() in Page_Load) and that doesn't work either.</p>

<p>Anyway, the way that works is by simply taking the ControlsCollection of the Page, grabbing the control I need from that, getting it's collection, grabbing the next lower control and so forth.</p>

<p>I only have to do this seven times.  So I have eight foreach loops.</p>

<p>Basically, my code is like this:</p>

<p>///////////////////////////////
// On the page
///////////////////////////////</p>

<pre><code>ControlCollection controls = Controls;

foreach( Control control in controls)
{
   if ( string.Equals( control.ID, "FormID", StringComparison.InvariantCultureIgnore ) )
   {
      ControlCollection nextControls = control.Controls;

      foreach( Control nextControl in nextControls )
      {
         if ( string.Equals( nextControl.ID, "DivICareAboutInTheForm", StringComparison.InvariantCultureIgnor ) )
         {
             ControlCollection nextNextControls = nextControl.Controls;
             //:
             //:
             //Yes, it's that bad and so forth.
             //:
             //:
         }
      }
   }
}
</code></pre>
