3.5. Setting the Initial Focus to a Specific Control

Problem

You need to set the focus of a page to a specific control when the page is first loaded.

Solution

Create a client-side JavaScript block in the code-behind that sets the focus to the desired control and then writes the block to the rendered page so that it is executed when the page is loaded.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Write some code that is called from the Page_Load method and generates a client-side JavaScript block that calls the focus method of the desired control and sets the control’s initial focus to itself.

  2. Use the RegisterClientScriptBlock method of the Page object to register the script block so that it is output when the page is rendered.

Example 3-16 through Example 3-18 show the .aspx and code-behind files for the application that implements this solution. (See the sidebar, Building a JavaScript Library, for the rationale behind our approach.)

Discussion

To implement this solution, nothing special is required in the .aspx file. But the code-behind page is another matter. There you need to generate a client-side JavaScript block that calls the focus method of the desired control and sets the control’s initial focus to itself.

The application that we’ve written to implement the solution uses a simple form with only three text boxes to capture the user’s first name, last name, and age. The application’s code-behind assembles a client-side JavaScript block that calls ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.