JavaScript Editor jscript editor     Web designer 



Main Page

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.

NoteNote

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:

    Visual BasicВ CopyCode imageCopy Code
    Protected Sub Page_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs)
        TextBox1.Focus()
    End Sub

    C#В CopyCode imageCopy Code
    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:

    Visual BasicВ CopyCode imageCopy Code
    <%@ 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>
C#В CopyCode imageCopy Code
<%@ 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



JavaScript Editor jscript editor     Web designer