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.
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?
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.
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)
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
Works for me, man. If you have a more elegant solution, let me know. You can email me at RogerMcCook@hotmail.com.
Roger D. McCook
McCook Software, Inc.