In ASP.NET 4.0, you can use two methods to set focus on controls.
First, by using the control's Focus method. Second, calling page's SetFocus method and passing ID of the control in this SetFocus method.
The following code snippet sets focus on TextBox1 by calling its Focus method on Page load event.
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Focus();
}
The following code snippet sets focus on a TextBox control with ID TextBox1.
void Page_Init(object sender, EventArgs e)
{
SetFocus(TextBox1);
}
You can also set the default focus on a control by using the defaultfocus tag of a Form.
The following code snippet sets default focus on TextBox1.
<form id="form1" runat="server" defaultfocus="TextBox1" >
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
</div>
</form>
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.
Gowtham RajamanickamPosted Apr 7, 2016, 3:01 AM
good one..
anand sengarPosted Jan 24, 2011, 3:05 AM
use this code for any controll- ControlId.Focus();
knightseditedPosted Jan 18, 2011, 12:57 PMEdited Jan 18, 2011, 12:57 PM
Hi John, Nice tip, in my opinion this item and any similar to this should go the "How do i" section of the website.what you think ?Thanks