CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to Set Default Focus on a ASP.Net Control in PageLoad or Postback?
Submitted By Satheesh Babu B
On 3/24/2009 7:10:23 AM
Tags: ASP.Net,CodeDigest  

How to set default focus on a ASP.Net control in PageLoad or Postback?

 

When we have an input form, it will be good if we set a default focus on the first input control. It can be done in variety of ways in asp.net applications.

 

This little article will discuss some of the methods to achieve the same.

1st Method

From ASP.Net 2.0, every control has a method called Focus() which we can use to set the focus. Refer the below code,

 

protected void Page_Load(object sender, EventArgs e)

    {

        txtName.Focus();      

    }  

 

2nd Method

We can call the SetFocus() method either by passing the server control or ClientID of any control. Refer the below code,

protected void Page_Load(object sender, EventArgs e)

    {      

      Page.SetFocus(txtName);

    }

 

3rd Method

We can set the default control focus using defaultfocus property of form tag.

<form id="form1" runat="server" defaultfocus="txtName">

 

Using JavaScript

We can also use javascript focus() method to set focus on a input control.

protected void Page_Load(object sender, EventArgs e)

    {      

     if(!Page.ClientScript.IsStartupScriptRegistered("focus"))

        Page.ClientScript.RegisterStartupScript(Page.GetType(), "focus", "document.getElementById('" + txtName.ClientID + "').focus();",true);

    }

Hope this little artcile will help someone!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..