How to set focus to a web control in ASP.NET

Posted by Dan7el on Stack Overflow See other posts from Stack Overflow or by Dan7el
Published on 2010-04-06T20:32:35Z Indexed on 2010/04/06 20:43 UTC
Read the original article Hit count: 318

Filed under:
|

Question: What is the best way to set focus to a web control in ASP .NET.

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.

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.

I know I could possibly do: document.getElementById( "<%= 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 "<% %>" in the page. GAH.

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

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.

I only have to do this seven times. So I have eight foreach loops.

Basically, my code is like this:

/////////////////////////////// // On the page ///////////////////////////////

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.
             //:
             //:
         }
      }
   }
}

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about web-development