What is the best solution of defaultButton and "Enter key pressed" for ASP.NET 2.0-3.5 forms?
2 Answers
Just add the "defaultbutton" attribute to the form and set it to the ID of the button you want to be the default.
<form defaultbutton="button1" runat="server">
<asp:textbox id="textbox1" runat="server"/>
<asp:button id="button1" text="Button1" runat="server"/>
</form>
NOTE: This only works in ASP.NET 2.0+
1 Comment
Anatoly Mironov
If you want to bind enter key to a a specific area of your form, add an additional
<asp:Panel id="myNewPanel" runat="server" DefaultButton="sendEmailButton">your buttons and textboxes</asp:Panel>Since form submission on hitting the enter key is a part of life with HTML, you'll have to trap the Enter key using javascript and only allow it to go through when it's valid (such as within textareas). Check out http://brennan.offwhite.net/blog/2004/08/04/the-single-form-problem-with-aspnet/ for a good explanation.