Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Setting focus to Textbox after Page Loads

Posted by Ravi Varma Thumati on May 5, 2009

In this code snippet, you will see how you can set the focus to a textbox either after the page loads for the first time or after post back. 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”, “<scriptJscript”” > document.getElementById(“”Textbox1″”).focus(); </Script>”)

This will set the focus to the textbox right after the page loads.

Advertisements

One Response to “Setting focus to Textbox after Page Loads”

  1. F*ckin’ awesome issues here. I’m very happy to peer your post. Thanks so much and i’m taking a look forward to contact you. Will you please drop me a e-mail?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: