Enter Key Default Submit Button

Enter key behavior works a little differently in ASP.NET.

With a single button on the form it is straightforward, since that button is the only one and therefore the default. With two or more buttons, the first one becomes the default, which is often not the one you want.

ASP.NET 2.0 introduced the defaultbutton property to handle this. Set it to the ID of the <asp:Button> whose event you want to fire.

The property can be set on the <form> tag and on the <asp:Panel> tag. A panel level setting overrides the form level setting for the controls inside that panel.

If neither of those fits how your page is put together, JavaScript can handle it. This function relies on a custom FindControl helper:

function Submit(e, ButtonName)
{
    var KeyCode = (window.event) ? event.keyCode : e.which;
    var KeyChar = (window.event) ? String.fromCharCode(event.keyCode)
                                 : String.fromCharCode(e.which);

    if (KeyCode == 13)
    {
        var btnSubmit = FindControl(ButtonName, "input");

        if (btnSubmit != null)
        {
            btnSubmit.click();
        }

        if (window.event)
        {
            window.event.returnValue = false;
        }
        else
        {
            e.preventDefault();
        }
    }
}

Then on any control on the page you can specify which button should be clicked when the Enter key is pressed while that control has focus:

<asp:TextBox ID="txtTest" onkeypress="Submit(event, 'btnSubmit')" runat="server" />