Single post

Set Initial Focus on Page [ASP.NET/C#]

If you want to set Initial Focus on a page, here is a simple function that allows you to do just that. I usually have this in my Global.asax.cs file and call it on every page with a form.

public static void SetFocus(System.Web.UI.Page pg, string ControlName)
  {
  System.Text.StringBuilder jScript = new System.Text.StringBuilder();

  jScript.Append("< script language='JavaScript' >");
  jScript.Append("document.getElementById('" + ControlName + "').focus();");
  jScript.Append("< /script >");

  pg.RegisterStartupScript("setFocus", jScript.ToString());
  }

Before and after the >< symbols, there is no need for a space! Now, to use this function, use the following code in any form’s Page_Load event:

if (!this.IsPostBack)
  Global.SetFocus(this.Page, "ControlName");

Where ControlName is the name of the first control you want to set focus to. It’s also a good practice to set tabindex for all controls on the form.

Eponine
December 1st, 2004 at 8:51 pm

It works great! Thanks a lot to share this.
I was going mad using OnLoad=“document.FormName.ControlName.focus();”, it keep gaving me an error on the production server (although not in the development server). Your code works perfectly on both.

Jesse
December 30th, 2004 at 2:43 am

Thank you so much for this wonderful code! It works like a charm.

Thanks as well for the comment about the space before and after the >< symbols – you’re right, they aren’t necessary (they actually caused my code to fail). Once I removed the spaces, everything worked great!

Thanks again!!!

Naeem Charolia
March 14th, 2005 at 5:53 pm

thx boss!!! thats wounderful one …

Colleen
August 19th, 2005 at 2:28 pm

Thanks, I’ve been struggling with this for a while.

Shawn
November 11th, 2005 at 8:36 am

Thanks Mate for sharing the code.

Kim
February 2nd, 2006 at 1:22 am

Awesome—saved me a lot of time and stress—thanks!

LEAVE A COMMENT

theme by teslathemes