Set focus to textbox in ASP.NET Login control on page load

anD666 picture anD666 · Jun 15, 2010 · Viewed 57.8k times · Source

I am trying to set the focus to the user name TextBox which is inside an ASP.NET Login control.

I have tried to do this a couple of ways but none seem to be working. The page is loading but not going to the control.

Here is the code I've tried.

SetFocus(this.loginForm.FindControl("UserName"));

And

TextBox tbox = (TextBox)this.loginForm.FindControl("UserName");
if (tbox != null)
{    
  tbox.Focus();
} // if

Answer

Hoang Tran picture Hoang Tran · Sep 18, 2011

I'm using Page.Form.DefaultFocus and it works:

// inside page_load, LoginUser is the Login control
Page.Form.DefaultFocus = LoginUser.FindControl("Username").ClientID;