Set focus to textbox in ASP.NET Login control on p

2019-01-25 04:39发布

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

9条回答
在下西门庆
2楼-- · 2019-01-25 04:46

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>
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-25 04:51

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

// inside page_load, LoginUser is the Login control
Page.Form.DefaultFocus = LoginUser.FindControl("Username").ClientID;
查看更多
对你真心纯属浪费
4楼-- · 2019-01-25 04:54

None of the above answers worked for me, so I simply tried:

protected void Page_Load(object sender, EventArgs e) {
    // This works for me
    TxtMyTextBoxName.Focus();
}

... and it worked!
With an ASP TextBox defined as:

<asp:TextBox ID="TxtMyTextBoxName" type="search" runat="server"></asp:TextBox>
查看更多
三岁会撩人
5楼-- · 2019-01-25 04:55

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();
}
查看更多
男人必须洒脱
6楼-- · 2019-01-25 04:57
protected override void OnPreRender(EventArgs e)
{
        base.OnPreRender(e);
        Login.FindControl("UserName").Focus();

}
查看更多
老娘就宠你
7楼-- · 2019-01-25 05:00
protected void Page_Load(object sender, EventArgs e)
{
    SetFocus(LoginCntl.FindControl("UserName"));
}
查看更多
登录 后发表回答