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:
Write some code that is called from the
Page_Loadmethod 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.Use the
RegisterClientScriptBlockmethod of thePageobject 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access