LANGUAGES: VB .NET
ASP.NET VERSIONS: 1.0 | 1.1
One of the most common questions I get asked by developers is how to set focus to a particular control when a form loads. By setting focus to a control you enable the end user to begin typing instead of having to click on a form or control. With a little code, you can even make this dynamic and data-driven.
Add the following procedure to your Web Form or your custom base class (see related tip on custom base classes at http://www.aspnetpro.com/NewsletterArticle/2003/05/asp200305mc_l/asp200305mc_l.asp):
Private Sub SetFocus(ByVal FocusControl As Control)
Dim Script As New System.Text.StringBuilder
Dim ClientID As String = FocusControl. ClientID
Before you use this function, let's look at what it's doing. Start by passing a reference into the control that you want to utilize. The function uses this reference to obtain the ClientID of the control.
Now that you know what the SetFocus function does, let's look at two ways to use it. The simplest approach is to call the function to set focus to control on the page load event:
Private Sub Page_Load( ... )
If IsPostBack Then Exit Sub
In this code, the TextBox2 control receives focus when the page loads. This could be done dynamically or in response to an event, as the following command button code shows:
Private Sub Button1_Click( ... )
This code will set the focus to TextBox3 whenever Button1 is clicked.
With a few easy lines of server-side code you can control the focus on a Web Form as the page loads in the browser. Setting focus to a control lets you make your application interface more productive and more keyboard-friendly for data entry.
Got a UI question, tip, or idea for a topic you'd like me to cover? I'd love to hear it. E-mail me at [email protected].
This article's sample code is available for download.
Brad McCabe is the technical evangelist for Infragistics. Brad also has been a systems architect and consultant for Verizon Communications and many other clients, and he was a leading .NET evangelist within Ajilon Consulting. His primary interests include ASP.NET, Windows CE .NET, .NET Compact Framework, and Microsoft's networking technologies. E-mail him at [email protected].