>
 





In ASP.NET 1.x, it is not possible to programmatically set focus to a web server control without using the JavaScript's focus() function after submit (on Page Load / after Postback). You may find the details on how to set focus to web controls in ASP.NET 1.x in one of my previous articles: Set Focus After PostBack in ASP.NET 1.x - Setting Focus to an ASP.NET Control

However, in ASP.NET 2.0 and in ASP.NET 3.5, there are three ways to dynamically set the focus to a specific control using just one line of code.

METHOD 1 – Set Focus in ASP.NET 2.0/3.5 Using Page’s SetFocus() Method After Submit (on Page Load / after Postback)


You pass the control ID as the parameter and call the Page.SetFocus(control) method, which enables you to set the focus to a particular control immediately after a page is initiated,loaded or postbacked.


void Page_Init(object sender, EventArgs e)
{
  SetFocus(ControlToSetFocus);
}

METHOD 2 – Set Focus in ASP.NET 2.0/3.5 Usign Web Controls’ Focus() Method  After Submit (on Page Load / after Postback)


Or you can call the Focus() method that is available to all web controls. You can call it in the Page_Load event. For example, if you have a TextBox web control called Textbox1, you may simply call:

TextBox1.Focus();

METHOD 3 - SET FOCUS in ASP.NET 2.0/3.5 Using DefaultFocus Property After Submit (on Page Load / after Postback)


ASP 2.0 web forms also have a property called DefaultFocus. By setting the DefaultFocus property, you can set the focus to a desired control when page loads.

For example, the code below will automatically set the focus on TextBox2 when the web form is loaded:

<form defaultfocus="textbox2" runat="server">
  <asp:textbox id="textbox1" runat="server"/>
  <asp:textbox id="textbox2" runat="server"/>
</form>

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Comments

December 8. 2008 04:42

good

good | Reply

October 20. 2009 16:01

Social comments and analytics for this post

This post was mentioned on Twitter by bloggingdev: 3 Methods to Set Focus on Page Load / After Postback / After Submit in ASP.NET - http://bit.ly/J51ON

uberVU - social comments | Reply

December 26. 2009 19:29

Just try to smile for about 2-3 mins then you can get back to work

cash loans | Reply

Add comment




(Will not be displayed!)