Recipe 4.5. 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.

Building a JavaScript Library

Client-side JavaScript is frequently required in web pages, and to want to reuse the same JavaScript block is common. In classic ASP, reuse is achieved by using include files or by linking to specific JavaScript files. A big drawback to either of these techniques is that when the files are used as libraries, as is commonly done, they typically contain more functions than needed by any given pages. This results in slower performance because the excess code has to be downloaded to the browser along with the required code. Other options include using many files, each containing fewer methods, or putting the functionality required for a specific page directly in that page. Both result in duplication of JavaScript in many places and a maintenance headache when changes are required.

With ASP.NET, you can generate the JavaScript you need by writing specialized methods that you encapsulate in a custom helper class. You call only the methods required to create the JavaScript you need for a specific page. This approach lets you reuse debugged JavaScript for all of your applications, and it improves performance because only the needed functions are rendered in the HTML page. An example of a client script library class that contains the setFocusToControl method used in this recipe is shown here. To make the method more useful, we have modified the code to allow you to pass at runtime the identity of the control to receive focus. In addition, the method has the Shared attribute to allow calling the method without instantiating the class.

 Namespace DDIG.Script   Public Class ClientScripts   Private Shared Sub setFocusToControl( _ ByVal pageControl As System.Web.UI.Page, _ ByVal scriptManager As System.Web.UI.ClientScriptManager, 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   scriptManager.RegisterStartupScript(pageControl.GetType(), _       "SetFocusScript", _   scriptBlock, _   True)   End Sub 'setFocusToControl     End Class   End Namespace 


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  Runat="server" ContentPlaceHolder>  <div align="center" >    Setting Control Focus - Approach 2 (VB)  </div>  <table width="75%" align="center" border="0" >    <tr>       <td >First Name: </td>       <td>          <asp:TextBox  Runat="server"   Columns="30" Css />          <asp:RequiredFieldValidator    Runat="server"   ControlToValidate="txtFirstName"   Css   Display="Dynamic"   EnableClientScript="True">   <img src="/books/1/505/1/html/2/images/arrow_alert.gif"   alt="arrow"/> First Name Is Required  </asp:RequiredFieldValidator> </td>   </tr> <tr>    <td >Last Name: </td>        <td>       <asp:TextBox  Runat="server"   Columns="30" Css />   <asp:RequiredFieldValidator    Runat="server"   ControlToValidate="txtLastName"   Css   Display="Dynamic"   EnableClientScript="True">       <img src="/books/1/505/1/html/2/images/arrow_alert.gif"   alt="arrow"/> Last Name Is Required  </asp:RequiredFieldValidator> </td>   </tr>  <tr> <td >Age: </td> <td>   <asp:TextBox  Runat="server" Columns="30" Css />           <asp:RequiredFieldValidator   Runat="server"   ControlToValidate="txtAge"  Css  Display="Dynamic"  EnableClientScript="True">   <img src="/books/1/505/1/html/2/images/arrow_alert.gif"  alt="arrow"/> Age Is Required   </asp:RequiredFieldValidator>  <asp:RangeValidator  Runat="server"    ControlToValidate="txtAge"    Css    Display="Dynamic"    EnableClientScript="True"    MinimumValue="18"    MaximumValue="99"     Type="Integer">  <img src="/books/1/505/1/html/2/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  runat="server" type="button"    value="Save" causesvalidation="true"    onserverclick="btnSave_ServerClick"/>  </td> <td align="center">    <input  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 } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net