O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required