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>
Currently rated 3.7 by 3 people
- Currently 3.666667/5 Stars.
- 1
- 2
- 3
- 4
- 5