>
 





If you try to use Enter key in ASP.NET, according to your browser type, you can get really weird results. In my previous article Default Button in ASP.NET 1.1, I described two methods to make enter key default button for form inputs in ASP.NET 1.1.

Fortunately, ASP.NET 2.0 makes this easier by introducing a concept of "default button" that can be used with either a <form> or <asp:panel> control. What button will be "clicked" depends of where acutally cursor is and what button is choosen as a default button for form or a panel.

For example, with the below sample:

<html>
<body>
   <form defaultbutton=“button1” runat=“server”>
      <asp:button id=“button1” text=“btn1” runat=“server”/>
         <asp:panel defaultbutton=“button2” runat=“server”>
            <asp:textbox id=“textbox1” runat=“server”/>
            <asp:button id=“button2”  text="btn2" runat=“server”/>
          </asp:panel>
    </form>
</body>
</html>

If the enter key is selected the first time the page is loaded, "button1" will be the button that receives the post-back event. If the enter key is hit while the user has their cursor focus within the "textbox1" textbox (contained within the <asp:panel>), then "button2" will be the button that receives the post-back event. 

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!

Currently rated 3.5 by 4 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Comments

February 13. 2009 16:16

Ah! Thanks so much for this post. ASP.NET's insistence on a single server-side form per page is a bit of a bugbear of mine. Clearly this results in the annoying focus on the first button on the page whereas in olden days you'd have several (client-side) forms and the first button on the *form* that was focussed would get the keypress. This is the behaviour that users are likely to expect.

I was about to whip up some needlessly complex jQuery when I stumbled across your post documenting a .NET2.0 feature that I hadn't come across, which has allowed me to keep the default button selection in the C# where I won't lose it!
Thanks again
Jon.

Jon | Reply

October 22. 2009 14:55

Social comments and analytics for this post

This post was mentioned on Twitter by bloggingdev: Enter Key Default Button in ASP.NET 2.0 - Setting the enter key as default button for form inputs - http://su.pr/6pSdle

uberVU - social comments | Reply

December 26. 2009 19:25

I guess there's always an easier way ...

cash loans | Reply

Add comment




(Will not be displayed!)








Free CMS