19 August 2004
Set Initial Focus on Page [ASP.NET/C#]
Posted by Mikhail Esteves under: C#; Tips .
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.
6 Comments so far...
Eponine Says:
1 December 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 Says:
30 December 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 Says:
14 March 2005 at 5:53 pm.
thx boss!!! thats wounderful one …
Colleen Says:
19 August 2005 at 2:28 pm.
Thanks, I’ve been struggling with this for a while.
Shawn Says:
11 November 2005 at 8:36 am.
Thanks Mate for sharing the code.
Kim Says:
2 February 2006 at 1:22 am.
Awesome—saved me a lot of time and stress—thanks!