4.4. Setting the Initial Focus to a Specific Control Problem

Problem

You need to set the focus of a page to a specific control when the page is first loaded.

Solution

The simplest solution is to use the SetFocus method of the page object to set the focus to a specific control, as shown below:


	Page.SetFocus(txtFirstName)

	Page.SetFocus(txtFirstName);

Another more flexible solution is to create a client-side JavaScript block in the code-behind that sets the focus to the desired control and then writes the block to the rendered page so it is executed when the page is loaded. We focus on this solution from here on because using client-side JavaScript is often helpful, and occasionally a requirement, when working with forms.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Write some code that is called from the Page_Load method and generates a client-side JavaScript block that calls the focus method of the desired control and sets the control’s initial focus to itself.

  2. Use the RegisterStartupScript method of the ClientScript object to register the script block so it is output when the page is rendered.

Examples 4-13, 4-14 through 4-15 showthe .aspx and code-behind files for the application that implements this solution. (See the “Building a JavaScript Library” sidebar for the rationale behind our approach.)

Discussion

To implement the JavaScript-based solution, nothing special is required in the .aspx file. But the code-behind page is another matter. There, you need to generate a client-side JavaScript block that calls the focus method of the desired control and sets the control’s initial focus to itself.

The application that we’ve written to implement the solution uses a simple form with only three text boxes to capture the user’s first name, last name, and age. The application’s code-behind assembles a client-side JavaScript block that calls the set focus method of the first text box control and then writes the script block to the rendered page. Here is the code that sets the focus of the first text box on the form, txtFirstName:

	<script type="text/javascript">
	<!--
	document.getElementById('ctl00_PageBody_txtFirstName').focus();
	// -->
	</script>

The client-side JavaScript block is generated by the setFocusToControl method of the code-behind. You pass to setFocusToControl the reference to the control that you want to have the focus when the page is initially displayed in the browser, which is done via controlToFocus.ClientID in our example. The client-side JavaScript uses the getElementById method of the document object to get a reference to the passed control and then calls the focus method on the control:


	scriptBlock = "document.getElementById('" & _
				   controlToFocus.ClientID & "').focus();"

	scriptBlock = "document.getElementById('" +
				   controlToFocus.ClientID + "').focus();";

The RegisterStartupScript method of the Page object is used to register the client-side script block to be output when the page is displayed in the browser. This method outputs the script block at the bottom of the form. This is important because the script block created in the setFocusToControl method is executed when the browser parses the page; for it to work correctly, the controls on the form have to have been previously created. If this block were output at the top of the page or at the beginning of the form, a JavaScript error would occur because the control to set the focus to would not exist.

To set the initial focus, the Page_Load method calls the setFocusToControl method when the page is initially loaded, passing it a reference to the control that is to have initial focus.

With the basic functionality in place to set the focus to a control programmatically, many options are available. Refer to Recipe 4.5 for an example that uses the same functionality to set the focus to a control that has a validation error.

See Also

Recipe 4.5

Example 4-13. Setting focus initially (.aspx)

<%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"
  AutoEventWireup="false"
  CodeFile="CH04SetFocusVB2.aspx.vb"
  Inherits="ASPNetCookbook.VBExamples.CH04SetFocusVB2"
  Title="Setting Control Focus - Approach 2" %>
<asp:Content ID="pageBody" Runat="server" ContentPlaceHolderID="PageBody">
 <div align="center" class="pageHeading">
   Setting Control Focus - Approach 2 (VB)
 </div>
 <table width="75%" align="center" border="0" >
   <tr>
      <td class="labelText">First Name: </td>
      <td>
         <asp:TextBox id="txtFirstName" Runat="server"
						  Columns="30" CssClass="labelText" />
         <asp:RequiredFieldValidator id="rfvFirstName"
				  Runat="server"
				  ControlToValidate="txtFirstName"
				  CssClass="alertText"
				  Display="Dynamic"
				  EnableClientScript="True">
			  <img src="images/arrow_alert.gif"
				  alt="arrow"/> First Name Is Required
		 </asp:RequiredFieldValidator>
		</td>
	  </tr>
	<tr>
	   <td class="labelText">Last Name: </td>
       <td>
	      <asp:TextBox id="txtLastName" Runat="server"
						  Columns="30" CssClass="labelText" />
		  <asp:RequiredFieldValidator id="rfvLastName"
				  Runat="server"
				  ControlToValidate="txtLastName"
				  CssClass="alertText"
				  Display="Dynamic"
				  EnableClientScript="True">
		      <img src="images/arrow_alert.gif"
				  alt="arrow"/> Last Name Is Required
		 </asp:RequiredFieldValidator>
		</td>
	  </tr>
	 <tr>
		<td class="labelText">Age: </td>
		<td>
		  <asp:TextBox id="txtAge" Runat="server"
						Columns="30" CssClass="labelText" />
          <asp:RequiredFieldValidator id="rfvAge"
						 Runat="server" 
						 ControlToValidate="txtAge"
						 CssClass="alertText"
						 Display="Dynamic"
						 EnableClientScript="True">
					  <img src="images/arrow_alert.gif"
						 alt="arrow"/> Age Is Required 
		 </asp:RequiredFieldValidator>
		 <asp:RangeValidator id="rvAge" Runat="server"
				   ControlToValidate="txtAge"
				   CssClass="alertText"
				   Display="Dynamic"
				   EnableClientScript="True"
				   MinimumValue="18"
				   MaximumValue="99" 
				   Type="Integer">
	 <img src="images/arrow_alert.gif"
					alt="arrow"/> Age Must Be Between 18 and 99
		 </asp:RangeValidator>
		</td>
	  </tr>
	 <tr>
		<td colspan="2">
		    <br/>
			<table align="center" width="50%">
			 <tr>
			   <td align="center">
			    <input id="btnSave" runat="server" type="button"
						   value="Save" causesvalidation="true"
						   onserverclick="btnSave_ServerClick"/>
				 </td>
				<td align="center">
				   <input id="btnCancel" runat="server" type="button"
							 value="Cancel" causesvalidation="false"/>
				</td>
			 </tr>
		  </table>
	   </td>
	 </tr>
   </table>
</asp:Content>

Example 4-14. Setting focus initially (.vb)

Option Explicit
On Option Strict On

Namespace ASPNetCookbook.VBExamples
	 ''' <summary>
	 ''' This class provides the code behind for
	 ''' CH04SetFocusVB2.aspx
	 ''' </summary>
Partial Class CH04SetFocusVB2
	Inherits System.Web.UI.Page
	
	'''********************************************************************
	''' <summary>
	''' This routine provides the event handler for the page load event. It
	''' is responsible for initializing the controls on the page.
	''' </summary>
	'''
	''' <param name="sender">Set to the sender of the event</param>
	''' <param name="e">Set to the event arguments</param>
	Protected Sub Page_Load(ByVal sender As Object, _
							ByVal e As System.EventArgs) Handles Me.Load
	  If (Not Page.IsPostBack) Then
		setFocusToControl(txtFirstName)
	  End If
    End Sub 'Page_Load

	'''********************************************************************
	''' <summary>
	''' This routine provides the event handler for the save button click
	''' event.
	''' </summary>
	'''
	''' <param name="sender">Set to the sender of the event</param>
	''' <param name="e">Set to the event arguments</param>
	Protected Sub btnSave_ServerClick(ByVal sender As Object, _	
								 ByVal e As System.EventArgs)
	  If (Page.IsValid) Then
		'process form data and save as required for application
	  End If
	End Sub 'btnSave_ServerClick

   '''*********************************************************************
   ''' <summary>
   ''' This routine generates the client script to set the focus to the
   ''' passed control
   ''' </summary>
   '''
   ''' <param name="controlToFocus">Set to the control to which focus is
   '''										 to be set</param>
   Private Sub setFocusToControl(ByVal controlToFocus As System.Web.UI.Control)
		Dim scriptBlock As String

		'add the client script to set the control focus
	   scriptBlock = "document.getElementById('" & _
					controlToFocus.ClientID & "').focus();"

	  'register the client script to be output when the page is rendered
	  ClientScript.RegisterStartupScript(Me.GetType(), _
										"SetFocusScript", _
										 scriptBlock, _
										 True)
										 
	  End Sub 'setFocusToControl
    End Class 'CH04SetFocusVB2
 End Namespace

Example 4-15. Setting focus initially (.cs)

using System;
namespace ASPNetCookbook.CSExamples
{
	/// <summary>
	/// This class provides the code behind for
	/// CH04SetFocusCS2.aspx
	/// </summary>
	public partial class CH04SetFocusCS2 : System.Web.UI.Page
	{
	
	 ///******************************************************************
	 /// <summary>
	 /// This routine provides the event handler for the page load event.
	 /// It is responsible for initializing the controls on the page.
	 /// </summary>
	 ///
	 /// <param name="sender">Set to the sender of the event</param>
	 /// <param name="e">Set to the event arguments</param>
	 protected void Page_Load(object sender, EventArgs e)
	 {
		if (!Page.IsPostBack)
		{
			setFocusToControl(txtFirstName);
		}
	} // Page_Load

    ///********************************************************************
	/// <summary>
	/// This routine provides the event handler for the save button click
	/// event.
	/// </summary>
	///
	/// <param name="sender">Set to the sender of the event</param>
	/// <param name="e">Set to the event arguments</param>
	protected void btnSave_ServerClick(Object sender,
									   System.EventArgs e)
	{
		if (Page.IsValid)
		{
		   // process form data and save as required for application
		}
	} //btnSave_ServerClick
	
	///********************************************************************
	/// <summary>
	/// This routine generates the client script to set the focus to the
	/// passed control
	/// </summary>
	///
	/// <param name="controlToFocus">Set to the control to which focus is
	/// to be set</param>
	private void setFocusToControl(System.Web.UI.Control controlToFocus)
	{
		String scriptBlock;

		// add the client script to set the control focus
		scriptBlock = "document.getElementById('" +
					 controlToFocus.ClientID + "').focus();";

		// register the client script to be output when the page is rendered
		ClientScript.RegisterStartupScript(this.GetType(),
										   "SetFocusScript",
										   scriptBlock,
										   true);

	} // setFocusToControl
  } // CH04SetFocusCS2
}

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.