Monday, June 30, 2008

A dozen ways to set focus to an ASP.NET control

Allowing keyboard navigation and improving the User Experience for users is usually a concern for web developers. Some use Flash frontends while others go the AJAX route but in the end it's the simple things that matter, such as setting the focus to a input element on a form.

Setting the focus on an ASP.NET control is quite simple in ASP.NET and there are at least half a dozen ways to do it.

Through server-side ASP.NET code, you can:
1. Set the DefaultFocus property of the form (you can also do this in the ASPX file for simplicity)
2. Call Control.Focus()
3. Call Page.SetFocus(controlId)

Through JavaScript:
4. Call document.getElementById(control.UniqueID/ClientID).focus(); either through Page.ClientScript.RegisterStartupScript
5. Same as 4, but using the onload javascript event
6. document.FormId.ElementId.focus()

If you just want to handle the onblur event of a control to set the focum on another control, you might also want to look at TabIndex, which sets the order in which the controls change focus on pressing Tab.

No comments: