devxlogo

Moving the focus on a control when the page loads

Moving the focus on a control when the page loads

ASP.NET doesn’t provide a built-in method for giving a control the input focus when the page loads. In fact, you can assign the TabIndex properties to controls on a page, but you can’t use this property to set the initial focus on a control of your choice.

The following procedure provides you with the ability to do exactly this

Sub SetControlFocus(ByVal ctrl As Control)    Dim code As String = String.Format("", ctrl.ClientID)    ctrl.Page.RegisterStartupScript("SetControlFocus", code)End Sub

As you see, the procedure inserts a line of JavaScript that runs after the page has been loaded, and that gives the focus to the control you pass as an argument. Because the Page object is retrieved as a property of the control, you can store this routine in any module of your ASP.NET application. You typicall call this procedure from the Page_Load event:

Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles _    MyBase.Load    SetControlFocus( TextBox2 )End Sub

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist