Friday 11 January 2013

Set Focus over a Control on Postback/PageLoad


Set Focus over a Control on Postback/PageLoad


In this code snippet, you will see how you can set the focus to an textbox either after the page loads for the first time or after postback. In asp.net there is no direct way for setting focus after post back, you need to use client side script only.
  
For example to set the focus for an textbox:

 document.forms[0].Textbox1.focus();
          
Note: This method uses the name property of the textbox.
To use the id, you would use:

document.getElementById("Textbox1").focus();

For injecting client side script using code behind, you can either use registerstartupscript method or registerclientsidescript. In our case we need to use registerstartupscript, since we need to set the focus immediately after page loads. Registerstartupscript method will place the script just before form end tag. 
So this script will be executed after page loads. 
To set focus we need to write following code:


Page.RegisterStartupScript("SetFocus", "<script language=""Jscript"" > document.getElementById(""Textbox1"").focus(); </Script>");

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top