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.


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.
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!!!
thx boss!!! thats wounderful one …
Thanks, I’ve been struggling with this for a while.
Thanks Mate for sharing the code.
Awesome—saved me a lot of time and stress—thanks!