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
void Page_Init(object sender, EventArgs e)
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:
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"/>
Want automatic updates?
Subscribe to our RSS feed
Get Email Updates
sent directly to your inbox!