ARTICLE

How to Set Focus on a Control in ASP.NET

Posted by John Arcadella Articles | ASP.NET Controls in C# January 18, 2011
Quick tip on how to set focus on an ASP.NET control such as a TextBox or ComboBox.
Reader Level:


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>

Login to add your contents and source code to this article
post comment
     

use this code for any controll- ControlId.Focus();

Posted by anand sengar Jan 24, 2011

Agree

Posted by Mahesh Chand Jan 18, 2011

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

Posted by knights Jan 18, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter