Setting a default button inside nested controls

Posted Monday, February 5, 2007 9:00 AM by C-Dog's .NET Tip of the Day

I posted in the past that you could set the DefaultButton property on the form tag of an ASP.NET form to control which button's event gets fired when the user clicks the enter key. I thought that was a great feature, but I had always wondered how you set a default button when that button is sitting inside of another control. Obviously you can't specify a button inside of a control there since the form doesn't know anything about whats inside that child control.

When I posted that previous post, ASP.NET 2.0 wasn't even released yet. After doing further research I have discovered that the DefaultButton property is also available on the Panel control. This makes it very easy to ensure that your event fires when the user clicks the enter button. You can even have multiple panels in your page with the DefaultButton property. Here is an example below.

<asp:Panel id="MyPanel" runat="server" DefaultButton="Button2">
   <asp:TextBox id="MyTextBox" runat="server" />
   <asp:Button id="Button1" runat="server" />
   <asp:Button id="Button2" runat="server" />
<asp:Panel />

In this case when the user clicks the enter button, Button2's OnClick event would be fired.

If you are curious on how it works behind the scenes, basically it injects cheesey javascript code that looks for a keypress of 13 and then fires the button.

<div id="ctl07_MyPanel" onkeypress="BLOCKED SCRIPTreturn 
WebForm_FireDefaultButton(event, 'ctl07_SearchButton')">

Read the complete post at