Search code examples
asp.netauthenticationpageloadsetfocus

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


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

Solution

  • Are you using a ScriptManager on the Page? If so, try the following:

    public void SetInputFocus()
    {
        TextBox tbox = this.loginForm.FindControl("UserName") as TextBox;
        if (tbox != null)
        {
           ScriptManager.GetCurrent(this.Page).SetFocus(tbox);
        }
    }
    

    Update: Never used a multiview before, but try this:

    protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
    {
       SetInputFocus();
    }