There are only two industries that refer to their customers as "users". --Edward Tufte
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

Set Initial Focus on an ASP.NET Page

Easily generate the Javascript to set focus to any control on your ASP.NET page

By steve on January 09, 2007.
Updated on January 22, 2012.
Viewed 17,741 times (0 times today).
Article TypesLanguagesLanguagesSoftware DevelopmentTechnologiesTopics
SnippetC#JavascriptClient sideWeb BrowsersWeb

Summary

Contents

Setting the cursor focus to a particular element of a web page when it loads is a pretty common little feature, but it can be annoying to implement. Here I automated the process in a C# method. You only need to pass the Control to the method and it will register the Javascript and set focus on page load.

This code was adapted from work by Fons.Sonnemans@reflectionit.nl.

Setup a couple of text boxes to test by adding the following to your aspx page.

Example: How to use the SetInitialFocus method

Contents
<P><asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<P><INPUT id="htmlTextBox" type="text" runat="server">

Then call the following method from the Page_Load in the code behind file. Notice that this works for WebControls and HtmlControls.

Example: How to use the SetInitialFocus method

Contents
public void TestSetInitialFocus()
{
   //Snippets00004.SetInitialFocus(TextBox1);
   Snippets00004.SetInitialFocus(htmlTextBox);
}

If you load the test aspx page in your browser, you should see that the selected control has the cursor focus.

Here's the class:

The SetInitialFocus method embedded in a class.

Contents
namespace Cambia.CoreLib
{
   using System;
   using System.Text;
   using System.Web.UI;
   using System.Web.UI.WebControls;

   /// <summary>
   /// Useful C# snippets from CambiaResearch.com
   /// </summary>
   public class Snippets00004
   {

      public Snippets00004()
      {
      }

      public static void SetInitialFocus(Control control) 
      {
         if (control.Page.IsClientScriptBlockRegistered("InitialFocus"))
            return;

         if (control.Page == null) 
         {
            throw new ArgumentException(
               "The Control must be added to a Page before "
               + "you can set the IntialFocus to it.");
         }
         if (control.Page.Request.Browser.JavaScript == true) 
         {
            // Create JavaScript
            StringBuilder s = new StringBuilder();
            s.Append("\n<SCRIPT LANGUAGE='JavaScript'>\n");
            s.Append("<!--\n");
            s.Append("function SetInitialFocus()\n");
            s.Append("{\n");
            s.Append("   document.");

            // Find the Form
            Control p = control.Parent;
            while (!(p is System.Web.UI.HtmlControls.HtmlForm))
               p = p.Parent;
            s.Append(p.ClientID);

            s.Append("['");
            s.Append(control.UniqueID);

            // Set Focus on the selected item of a RadioButtonList
            RadioButtonList rbl = control as RadioButtonList;
            if (rbl != null) 
            {
               string suffix = "_0";
               int t = 0;
               foreach (ListItem li in rbl.Items) 
               {
                  if (li.Selected) 
                  {
                     suffix = "_" + t.ToString();
                     break;
                  }
                  t++;
               }
               s.Append(suffix);
            }

            // Set Focus on the first item of a CheckBoxList
            if (control is CheckBoxList) 
            {
               s.Append("_0");
            }

            s.Append("'].focus();\n");
            s.Append("}\n");

            if (control.Page.SmartNavigation)
               s.Append("window.setTimeout(SetInitialFocus, 500);\n");
            else
               s.Append("window.onload = SetInitialFocus;\n");

            s.Append("// -->\n");
            s.Append("</SCRIPT>");

            // Register Client Script
            if (!control.Page.IsClientScriptBlockRegistered("InitialFocus"))
               control.Page.RegisterClientScriptBlock("InitialFocus", 
                  s.ToString());
         }
      }

   }
}
Back to Top

User Comments (5)

Posted 2007 Apr 24 08:21 AM. reply
Steve,

Thank you very much. It works great!!!

J. Ortiz
Reply 2007 Apr 25 19:20 PM by steve. reply
Thanks, J. Always glad to get some positive feedback!
Replied 2007 Oct 04 05:08 AM by Danny. reply
Was this written for .NET 1.1? There is a Page.SetFocus in .NET 2.0?
Replied 2007 Oct 22 08:58 AM by J Dangle. reply
This is for 1.1. It will compile in 2.0, but there are several warnings for obsolete pieces of code. I am also searching for a 2.0 version of this script.
Reply 2007 Oct 22 23:21 PM by steve. reply
In 2.0 .NET makes this easier. The .Focus() method on web controls injects the javascript to set focus to the control when the page loads.

txtName.Focus();
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.