3.6. Setting the Focus to a Control with a Validation Error

Problem

You want to set the focus to the first control on your form that has a validation error.

Solution

The solution to this recipe is an extension of the one introduced in Recipe 3.5, where we recommend writing code that generates some client-side JavaScript that calls the focus method of the desired control. For this recipe, we recommend adding some additional JavaScript-generating code that is tied to the Save button’s click event handler and that, when executed, searches for a control with a validation error and sets the focus to that control.

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 (see Recipe 3.5 for details).

  2. Add additional code to the Save (or equivalently named) button’s click event handler that searches for a control with a validation error and sets the focus to that control.

  3. 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-19 and Example 3-20 show routines that are required to implement the last two steps of this solution.

Discussion

As described in Recipe 3.5, you start implementing this solution by creating a client-side JavaScript block in the code-behind that sets the focus to a ...

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.