views:

589

answers:

2

Hiya,

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
+2  A: 

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();
}
GenericTypeTea
@Aristos - Thanks for pointing that out, I just copied and pasted my own SetInputFocus method and forgot to change it for this question.
GenericTypeTea
Still nothing, it is getting to the `ScriptManager.GetCurrent(this.Page).SetFocus(tbox);` statement but still doesnt set the focus
anD666
@anD666 - Updated my answer, give it a try. Just a guess, so it's untested. I just robbed the idea of a google search result.
GenericTypeTea
I think it is a problem with the master page. I tried copying the login control into a clean page and your code worked fine. Using the master page it doesnt seem to find the form with runat="server". I think I will remove it from a master page. Thank you
anD666
@GenericTypeTea The script manager wasnt on the master page, I have tried moving it onto that and it still cannot find a form with the tag runat=server. This form is on the master page and i cant add another to the webform.
anD666
A: 

You may try to do the following:

-Register two scripts (one to create a function to focus on your texbox when page is displayed, second to register id of the textbox)

this.Page.ClientScript.RegisterStartupScript(this.GetType(), "on_load", 
                "<script>function window_onload() \n { \n if (typeof(idLoginTextBox) == \"undefined\" || idLoginTextBox == null) \n return; \n idLoginTextBox.focus();\n } \n window.onload = window_onload; </script>");

this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Focus", String.Format("<script>var idLoginTextBox=document.getElementById(\"{0}\").focus();</script>", this.loginForm.ClientID));             

As the result you should get the following in your code:

      <script>
          function window_onload()
          {
            if (typeof(idLoginTextBox) == "undefined" || idLoginTextBox == null)
                return;     
            idLoginTextBox.focus();
        }
        window.onload = window_onload;     
      </script>   



<script>
        var idLoginTextBox=document.getElementById("ctl00_LoginTextBox").focus();
  </script>
Konrad