How to force [ENTER] key form submit behavior on a Button
By Peter Bromberg
One of the most annoying behaviors in an ASP.NET application is having a TextBox to fill in and a Submit button. Many users are used to being able to fill in the textbox and hit the [ENTER] key and have the form properly submit.
This doesn't always work in ASP.NET - in some cases nothing happens, in others the FORM posts back, but the button's event handler never fires, so your business logic doesn't work.
The easiest and most reliable way to correct this is to wrap the code block in an
asp:Panel control with its DefaultButton="Button1" attribute set (or
whatever is the correct ID of your submit button).
Now when users hit the [ENTER] key, your form will submit AND the button_click handler
will fire correctly.
Typical markup:
<asp:Panel ID = pnl1 DefaultButton="Button1" runat=server>
<!-- your textbox and button controls here -->
</asp:Panel>
In a MasterPage, this attribute on the Panel control translates to something like
the following:
<div id="contentLeftSide_pnl1" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'contentLeftSide_Button1')">
As can be seen above, the Panel (which renders as a DIV element) gets an onkeypress
event that fires the Form's FireDefaultButton event, passng to it the client
Id of the desired button.
You can have multiple such Panels on a page, each controlling a different button.
How to force [ENTER] key form submit behavior on a Button (1810 Views)