Extremely easy way of setting focus on an ASP.NET control

Just came across something new with ASP.NET, the Page.RegisterStartupScript method. This allows you to set (and change on the fly) a bit of JavaScript to run every time the page is posted back.

The nice thing about it is that you just call it with the name of the control you wish to set the focus on, rather than the mucking around I've seen with other solutions. Say you have a Button control called btnAddUser, you'd set focus to it with the nice elegant SetFocus(btnSomeButton). Or say you have a textbox called tbSubject that you want to have get focus after btnSomeButton was clicked, in the Click handler for btnSomeButton, you'd put in SetFocus(tbSubject).

This comes in really handy when using AutoPostBack with textboxes. Even though you may have set a TabOrder on the text box, and following textboxes, when you activate AutoPostBack on a textbox to do some kind of validation, the tab order postioning gets reset to the address window of your browser. However, with this, you can do your validation, then depending on the results of the validation, you can then SetFocus to either the same textbox if validation failed, or the next textbox (or any other control) that would normally be next in the TabOrder. When doing this, still set the correct TabOrder for your controls, as generally with a textbox, the AutoPostback event is only invoked if text is entered or changed in the textbox. If someone is just "tabbing through" the textbox without changing the text, then the normal TabOrder functionality will cause the focus to progress to the next control.

The code that follows was found at: http://www.ondotnet.com/pub/a/dotnet/2003/09/15/aspnet.html

Private Sub SetFocus(ByVal ctrl As Control)
    ' Define the JavaScript function for the specified control.
    Dim focusScript As String = ""

    ' Add the JavaScript code to the page.
    Page.RegisterStartupScript("FocusScript", focusScript)
End Sub

Reply
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: http://www.law.cornell.edu/uscode/17/107.shtml . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.