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 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:

Note: This method uses the name property of the textbox.
To use the id, you would use:


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