In this article I have explained how to submit an ASP.Net Form when Enter Key is pressed in ASP.Net using the DefaultButton property of ASP.Net Form and ASP.Net Panel.

This can be done at Form Level as well as using Panels to submit different sections of an ASP.Net Form.

Default Button property ensures that whenever user presses Enter key the button that is set as default will be triggered.


Default Button in form.

One can set the default button at the form level meaning of all the buttons in the form the one that is set as default will be triggered whenever user presses Enter key.

To set the default button one has to do the following

<form id="form1" runat="server" defaultbutton="Button1">

<asp:Button ID="Button1" runat="server" Text="Button"

    OnClick = "Button1_Click" />

<asp:Button ID="Button2" runat="server" Text="Button"

    OnClick = "Button2_Click" />

<asp:Button ID="Button3" runat="server" Text="Button"

    OnClick = "Button3_Click" />

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</form>

You just need to provide the ID of the Button to the defaultbutton property and it is set as default.

If you want to do it from code behind refer below

C#

this.Form.DefaultButton = "Button1";

 

VB.Net

Me.Form.DefaultButton = "Button1"

 


Default Button in Master Page

When working with master pages if the button you want to set at default resides in the content page thus the ID of the controls in the content page tend to change hence in that case you need to do the following

C#

this.Form.DefaultButton = Button1.UniqueID;

 

VB.Net

Me.Form.DefaultButton = Button1.UniqueID

 

 

Default Buttons at Panel Level

Default buttons can also be set at the panel level using the DefaultButton property of the panel

<asp:Panel ID="Panel1" runat="server" DefaultButton = "Button1">

<asp:Button ID="Button1" runat="server" Text="Button"

    OnClick = "Button1_Click" />

<asp:Button ID="Button2" runat="server" Text="Button"

    OnClick = "Button2_Click" />

<asp:Button ID="Button3" runat="server" Text="Button"

    OnClick = "Button3_Click" />

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</asp:Panel>

This will be useful in case you need to set multiple default buttons and use them for specific set controls. So in that case you can place the button inside different panels and whenever user presses enter key within the scope of that panel the default button for that panel is triggered.

The same can be done from code behind

C#

Panel1.DefaultButton = "Button1";

 

VB.Net

Panel1.DefaultButton = "Button1"

 

In case you want to use this with Master Pages you will again need to provide the UniqueID in the same way as done for the explained for the Form Default Buttons earlier.