You want to set the focus to the first control on your form that has a validation error.
In the code-behind class for the page, use the .NET language of your choice to:
Examples 4-16 and 4-17 show routines required to implement the last two steps of this solution.
This solution relies on the page object containing a collection of the validation controls on the form. The order of the validators in the collection is the same as the order in which they appear in the .aspx file. (The validators should be placed with the controls they validate for this solution to work correctly.)
To get a feel for how to implement this solution, first take a look at the sample application we created for Recipe 4.4 (Examples 4-13, 4-14 through 4-15). Next, consider the code in Examples 4-16 and 4-17, which is added to that application to implement this recipe's solution.
With the additional code, when the server-side button's click event is executed, a check is first made to see if the page is valid. If it is, a save operation will be performed. If the page is invalid, the validators will be iterated through until the first invalid one is found. This is determined by examining the IsValid property of each validator control; its value will be false if the control associated with the validator has failed to pass validation.
When an invalid validator is found, the associated control is identified by calling the FindControl method of the validator object. The control is then passed to the setFocusToControl method. Only one control can have the focus, so after an invalid control is found, the for loop is exited.
Example 4-16. Setting focus to control with validation error (.vb)
Example 4-17. Setting focus to control with validation error (.cs)