Extremely easy way of setting focus on an ASP.NET control
Posted: 6/17/2005 12:03:54 PM
By: Comfortably Anonymous
Times Read: 3,382
0 Dislikes: 0
Topic: Programming: Web Applications
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

Rating: (You must be logged in to vote)