Recipe 3.5 Setting the Initial Focus to a Specific Control

     

3.5.1 Problem

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

3.5.2 Solution

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 that it is executed when the page is loaded.

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 RegisterClientScriptBlock method of the Page object to register the script block so that it is output when the page is rendered.

Example 3-16 through Example 3-18 show the .aspx and code-behind files for the application that implements this solution. (See the sidebar, Building a JavaScript Library, for the rationale behind our approach.)

3.5.3 Discussion

To implement this 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 language='javascript'> <!--  document.frmSetFocus.txtFirstName.focus( );  //--> </script> 

The client-side JavaScript block is generated by the setFocus method of the code-behind. You pass to setFocus 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 bulk of the method code generates the opening and closing tags of the script block. The line that actually sets the focus to the desired control is built by concatenating the IDs of the form and the desired control:

 
figs/vbicon.gif
 clientScript.Append("document." &  frmSetFocus.ID  & "." & _  controlToFocus.ClientID  & ".focus( );" & _ NewLine) 
figs/csharpicon.gif
 clientScript.Append("document." +  frmSetFocus.ID  + "." +  controlToFocus.ClientID  + ".focus( );\n"); 

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 setFocus method is executed when the browser parses the page, and 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 yet exist.

To set the initial focus, the Page_Load method calls the setFocus 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 programmatically set the focus to a control, many options are available. Refer to Recipe 3.6 for an example that uses the same functionality to set the focus to a control that has a validation error.

3.5.4 See Also

Recipe 3.6

Building a JavaScript Library

Client-side JavaScript is frequently required in web pages, and it is not uncommon to want to reuse the same JavaScript block. 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 many more functions than are 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 is 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 setFocus method used in this recipe is shown here. To make the method even 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 Public Shared Sub setFocus( _ ByVal pageControl As System.Web.UI.Page, _ ByVal pageForm As HtmlForm, _ ByVal controlToFocus As System.Web.UI.Control) Dim clientScript As StringBuilder 'generate the opening script tag clientScript = New StringBuilder( ) clientScript.Append("<script & _ language='javascript'>" & vbCrLf) clientScript.Append("<!--" & vbCrLf) 'add the client script to set the control focus clientScript.Append("document." & _ pageForm.ID & "." & _ controlToFocus.ClientID & _ ".focus( );" & _ vbCrLf) 'generate the closing script tag clientScript.Append("//-->" & vbCrLf) clientScript.Append("</script>" & vbCrLf) 'register the client script to be output when 'the page is rendered pageControl.RegisterStartupScript( _ "setInitialFocus", _ clientScript.ToString( )) End Sub 'setFocus End Class End Namespace 


Example 3-16. Setting focus initially (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH03SetFocusVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH03SetFocusVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Set Control Focus</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmSetFocus" method="post" runat="server"> <table width="100%" cellpadding ="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Set Control Focus (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center"> <table 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"> 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"> 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"> 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"> 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"> <asp:ImageButton id="btnSave" Runat="server" CausesValidation="True" ImageUrl="images/ buttons /button_save.gif" /> </td> <td align="center"> <asp:ImageButton id="btnCancel" Runat ="server" CausesValidation="False" ImageUrl="images/buttons/button_cancel.gif" /> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </form> </body> </html> 

Example 3-17. Setting focus initially code-behind (.vb)
 Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH03SetFocusVB.aspx.vb ' ' Description: This module provides the code behind for ' CH03SetFocusVB.aspx ' '***************************************************************************** Imports System.Environment Imports System.Text Namespace ASPNetCookbook.VBExamples Public Class CH03SetFocusVB Inherits System.Web.UI.Page 'controls on form Protected frmSetFocus As System.Web.UI.HtmlControls.HtmlForm Protected txtFirstName As System.Web.UI.WebControls.TextBox Protected txtLastName As System.Web.UI.WebControls.TextBox Protected txtAge As System.Web.UI.WebControls.TextBox Protected WithEvents btnSave As System.Web.UI.WebControls.ImageButton Protected WithEvents btnCancel As System.Web.UI.WebControls.ImageButton '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load If (Not Page.IsPostBack) Then  setFocus(txtFirstName)  End If End Sub 'Page_Load '************************************************************************* ' ' ROUTINE: setFocus ' ' DESCRIPTION: This routine generates the client script to set the focus ' to the passed control '-------------------------------------------------------------------------  Private Sub setFocus(ByVal controlToFocus As System.Web.UI.Control)   Dim clientScript As StringBuilder   'generate the opening script tag   clientScript = New StringBuilder   clientScript.Append("<script language='javascript'>" & NewLine)   clientScript.Append("<!--" & NewLine)   'add the client script to set the control focus   clientScript.Append("document." & frmSetFocus.ID & "." & _   controlToFocus.ClientID & ".focus( );" & _   NewLine)   'generate the closing script tag   clientScript.Append("//-->" & NewLine)   clientScript.Append("</script>" & NewLine)   'register the client script to be output when the page is rendered   Page.RegisterStartupScript("ScriptBlock", _   clientScript.ToString( ))   End Sub 'setFocus  '************************************************************************* ' ' ROUTINE: btnSave_Click ' ' DESCRIPTION: This routine provides the event handler for the save ' button click event. It is responsible processing the ' form data. '------------------------------------------------------------------------- Private Sub btnSave_Click(ByVal sender As Object, _ ByVal e As System.Web.UI.ImageClickEventArgs) _ Handles btnSave.Click If (Page.IsValid) Then 'process form data and save as required for application End If End Sub 'btnSave_Click End Class 'CH03SetFocusVB End Namespace 

Example 3-18. Setting focus initially code-behind (.cs)
 //---------------------------------------------------------------------------- // // Module Name: CH03SetFocusCS.aspx.cs // // Description: This module provides the code behind for // CH03SetFocusCS.aspx // //**************************************************************************** using System; using System.Text; using System.Web.UI; namespace ASPNetCookbook.CSExamples { public class CH03SetFocusCS : System.Web.UI.Page { // controls on form protected System.Web.UI.HtmlControls.HtmlForm frmSetFocus; protected System.Web.UI.WebControls.TextBox txtFirstName; protected System.Web.UI.WebControls.TextBox txtLastName; protected System.Web.UI.WebControls.TextBox txtAge; protected System.Web.UI.WebControls.ImageButton btnSave; protected System.Web.UI.WebControls.ImageButton btnCancel; //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. //------------------------------------------------------------------------ private void Page_Load(object sender, System.EventArgs e) { // wire the save button click event this.btnSave.Click += new ImageClickEventHandler(this.btnSave_Click); if (!Page.IsPostBack) {  setFocus(txtFirstName);  } } // Page_Load //************************************************************************ // // ROUTINE: setFocus // // DESCRIPTION: This routine generates the client script to set the // focus to the passed control //------------------------------------------------------------------------  private void setFocus(System.Web.UI.Control controlToFocus)   {   StringBuilder clientScript;   // generate the opening script tag   clientScript = new StringBuilder( );   clientScript.Append("<script language='javascript'>\n");   clientScript.Append("<!--\n");   // add the client script to set the control focus   clientScript.Append("document." + frmSetFocus.ID + "." +   controlToFocus.ClientID + ".focus( );\n");   // generate the closing script tag   clientScript.Append("//-->\n");   clientScript.Append("</script>\n");   // register the client script to be output when the page is rendered   Page.RegisterStartupScript("ScriptBlock",   clientScript.ToString( ));   } // setFocus  //************************************************************************ // // ROUTINE: btnSave_Click // // DESCRIPTION: This routine provides the event handler for the save // button click event. It is responsible for processing // the form data. //------------------------------------------------------------------------ private void btnSave_Click(Object sender, System.Web.UI.ImageClickEventArgs e) { if (!Page.IsValid) { // process form data and save as required for application } } // btnSave_Click } // CH03SetFocusCS } 



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

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