How to set default focus to a control in ASP.NET WebForm after Page Loads?


When we  thinking how to solve this is problem  JavaScript comes in our mind And off course, that IS THE WAY TO GO.

ASP.NET 2.0 introduced DefaultFocus and DefaultButton properties for HtmlForm class that you can easily use for requirements like this.


DefaultFocus property gets or sets the child control on the HtmlForm that will receive the focus when the HtmlForm is loaded.

DefaultButton property gets or sets the child control of the HtmlForm that causes postback when enter key is pressed on the page.

Here is an example on how to use this two properties in your pages:

  <form id="formtest" runat="server" defaultfocus="txtfirstname" 
 defaultbutton="btnsubmit ">
    <div>
        Name:
        <asp:TextBox ID="txtfirstname btnsubmit" runat="server"></asp:TextBox><br />
        Address:
        <asp:TextBox ID="txtadress" runat="server"></asp:TextBox><br />       
        <asp:Button ID="btnsubmit" runat="server" Text="Submit" />&nbsp;       
        <asp:Button ID="btnsubmit" runat="server" Text="Cancel" />               
    </div>
    </form>

NOte: In order for this to work, your form must have runat="server" attribute set.
Tags: , , ,

Join Us!