Wednesday, December 28, 2005

 

Set Focus Using Javascript and C#

I ran into some trouble trying to get a Textbox on a User Control to have the cursor in it by default. I tried several Javascript tricks but nothing worked.

I finally tried adding the Javascript to the page through the code behind file using C# to see if that would help, and it did.

Here is the code I used:



protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

//Setfocus script
if ((username != null) &&
(!this.IsStartupScriptRegistered("SetControlFocus")))
this.RegisterStartupScript(
"SetControlFocus",
string.Format("<script language='JavaScript'>document" +
".getElementById('{0}').focus();</script>",
username.ClientID));
}

Comments: Post a Comment

Links to this post:

Create a Link



<< Home
Content copyright ©2003-2006 Tod Birdsall