Monday, January 7, 2008

Setting a Default Button to trigger when the Enter key is pressed in ASP.NET

One of the most frustrating things for users is filling out a form, hitting the Enter Button on their keyboard expecting the form to be submitted and instead some other UI element gets activated.

There are a few ways to handle this problem:

Setting the Form "defaultbutton" property

The easiest method to handle this problem is to set the form defaultbutton property for the page you are working on.

This is a great solution if you have a form on your page that is accessible. However, with the addition of ASP.NET MasterPages you don't always have access to the form element for the specified page (at least not easily.)

Example:

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



This is a great solution if you have a form on your page that is accessible. However, with the addition of ASP.NET MasterPages you don't always have access to the form element for the specified page (at least not easily.)

Use an ASP:Panel to define a context sensitive Default Enter Button
The ASP.NET Panel provides a super simple way to define a context sensitive default enter button when you have multiple buttons on a single page.

Example:

<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">         
Enter some text here for button 1:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" DefaultButton="Button2">
Enter some text here for button 2:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button2" runat="server" Text="Button" />
</asp:Panel>


The ASP.NET Panel needs to encompass the button that you want to trigger when the Enter key is pressed. Simply setting the DefaultButton property of the panel tells the panel which button to trigger when the Enter key is hit... voila. Context sensitive enter key triggers in about 30 seconds.

- Aaron

No comments: