Setting a default button in .NET

One way is to use a class like this to add an onkeydown client event to a to a textbox.

using System;
using System.Web.UI.WebControls;

namespace System.Web.UI.DefaultButton
{
      /// <summary>
      /// Methods to set default button
      /// </summary>
      class DefaultButton
      {
            /// <summary>
            /// Sets default button for the specified control
            /// </summary>
            Control name where user hits enter key</param>
            Button control to be called</param>
            void SetDefaultButton ( TextBox control , Button btButton )
            {
                  control.Attributes.Add("if(event.which ||
                  event.keyCode){if ((event.which == 13) ||
                  (event.keyCode == 13)) {document.getElementById('"+ btButton.ClientID+"').click();return false;}}
                  else {return true}; ");
            }

            /// <summary>
            /// Sets default button as the image button
            /// </summary>
            Control name where user hits enter key</param>
            Imagebutton to be called</param>
            void SetDefaultButton ( TextBox control , ImageButton btButton )
            {
                  control.Attributes.Add("if(event.which ||
                  event.keyCode){if ((event.which == 13) ||
                  (event.keyCode == 13)) {document.getElementById('"+ btButton.ClientID+"').click();return false;}}
                  else {return true}; ");
            }
      }
}

Another easier and quicker alternative is to place all the form elements in an ASP.NET Panel and then define the panelโ€™s default button property, like this:

<asp:Panel runat="btnHello">
    First name: <asp:TextBox runat="txtFirstName" />
    <asp:ImageButton ID="lbHello_Click" />
</asp:Panel><br /><br />

But of course if you are using a LinkButton, then its a whole another ball game. None of the techniques described above might work for you. But you are in luck, this page has what you need to get around that - Using Panel.DefaultButton property with LinkButton control in ASP.NET

If you liked this post, ๐Ÿ—ž subscribe to my newsletter and follow me on ๐•!