How to set input focus to a control in ASP.NET WebForm after Page Loads?
Copyright © 2007-2012 www.AspDotNetFaq.com
The first thing that comes to ones mind when thinking on how to solve this is - JavaScript.
And off course, that IS THE WAY TO GO, but why making your hands dirty writing client side scripts, embedding them in your Page HTML code, and testing on different browsers/version, when there is cleaner way of doing this?
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.
So here is an example on how to use this two properties in your pages:
<form id="SampleForm" runat="server" defaultfocus="FirstName" defaultbutton="Submit">
<div>
First Name:
<asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last Name:
<asp:TextBox ID="LastName" runat="server"></asp:TextBox><br />
<asp:Button ID="Submit" runat="server" Text="Submit" />
<asp:Button ID="Cancel" runat="server" Text="Cancel" />
</div>
</form>
TIP: In order for this to work, your form must have
runat="
server" attribute set.
Copyright © 2007-2012 www.AspDotNetFaq.com