Partager via


How to: Set Focus on ASP.NET Web Server Controls

If it is important in your application, you can put the focus on a specific ASP.NET Web server control by using server code. You can put the focus on a specific control dynamically, or you can specify a control that should get the focus by default. You can set the default focus for the form as a whole, or you can set the default focus on a control that is a child of a Panel control.

You can put the focus on the following types of controls:

You can also set the focus on controls that contain one or more of the controls listed above. For example, you can set the focus on a Login control. In that case, the focus will be put on the first eligible control within the Login control.

In general, if you set focus on a control that cannot receive focus or is hidden or disabled, the call is ignored. If you attempt to set focus on a non-visual control, such as a data source control, an exception is thrown.

Note

Setting focus requires that client scripting be enabled in the browser.

To set focus on an ASP.NET Web server control

  • Call the control's Focus method.

    -or-

  • Call the page's SetFocus method, passing it the ID of the control on which you want to set focus.

    The following code example shows how to set the focus on the control with the ID TextBox1:

    Security noteSecurity Note

    This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

    Protected Sub Page_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs)
        TextBox1.Focus()
    End Sub
    
    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Focus();
    }
    

To set default focus in a form or panel

  • Set the DefaultFocus attribute of the form element in the page or of a Panel control.

    The following code example shows a page with the default focus set to the control TextBox1:

    <%@ Page Language="VB" %>
    <html>
    <head runat="server">
      <title>Test Page</title>
    </head>
    <body>
      <form id="form1" runat="server" defaultfocus="TextBox1" >
        <div>
          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
          <br />
          <asp:Button ID="Button1" runat="server" Text="Button" />
          <br />
        </div>
      </form>
    </body>
    </html>
    
<%@ Page Language="C#" %>
<html>
<head runat="server">
  <title>Test Page</title>
</head>
<body>
  <form id="form1" runat="server" defaultfocus="TextBox1" >
    <div>
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
      <br />
      <asp:Button ID="Button1" runat="server" Text="Button" />
      <br />
    </div>
  </form>
</body>
</html>

See Also

Concepts

Tab Order, Focus, and Access Keys in ASP.NET Web Server Controls