Problem solve Get help with specific problems with your technologies, process and projects.

Setting the focus on an ASP.NET page

Get the cursor to automatically set to where you need to start typing.

This tip was submitted to the Visual Studio .NET Info Center Tip Exchange by member Roger McCook. Let other users know how useful it is by rating the tip below. Got a tip or code of your own you'd like to share? Submit it here.

The aggravation
You are traveling  to a web page where you will enter data. Your fingers hover expectantly over the keyboard. A thin line of saliva trickles down your chin. You dry your face in your sleeve without moving your fingers from the keyboard. Boom! The page has loaded but ... where is the cursor? Arrrrgh! You've got to reach over and grab the mouse and click in the textbox. Now you are ready to start typing. Sound familiar? 

Big deal
Is this a big deal? To the person who uses the page occasionally, it would be nice if the cursor were automatically set to where they need to start typing. Nice and thoughtful but not that big of a deal. To the person chained to the desk, using your page all day, it is a very big deal.

The solution
Here is the solution that seems to work best for me. In the code-behind file for a page (if you use code-behind), create a procedure named SetFocus as follows:

Private Sub SetFocus(ByVal ctrl As System.Web.UI.Control)
     Dim s As String = "<SCRIPT language='javascript'>document.getElementById('" & ctrl.ID & "').focus() </SCRIPT>"
     RegisterStartupScript("focus", s)

The following shows how you'd call the procedure to set the focus on a textbox named txtSerialNumber when the form first loads. This also will be in the code-behind file:

If Page.IsPostBack = False Then
    ' Blah Blah Blah All the other stuff you want to do
End If

Works for me, man. If you have a more elegant solution, let me know. You can email me at

Roger D. McCook
McCook Software, Inc.

Dig Deeper on ASP.NET development best practices

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.