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> public class DefaultButton { /// <summary> /// Sets default button for the specified control /// </summary> /// <param name="control">Control name where user hits enter key</param> /// <param name="btButton">Button control to be called</param> public static void SetDefaultButton ( TextBox control , Button btButton ) { control.Attributes.Add("onkeydown", "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> /// <param name="control">Control name where user hits enter key</param> /// <param name="btButton">Imagebutton to be called</param> public static void SetDefaultButton ( TextBox control , ImageButton btButton ) { control.Attributes.Add("onkeydown", "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="server" DefaultButton="btnHello"> First name: <asp:TextBox runat="server" ID="txtFirstName" /> <asp:ImageButton ID="btnHello" runat="server" Text="Click me" OnClick="lbHello_Click" /> </asp:Panel>
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
Tags: asp.net