ASP.NET Default "Enter" Button

Scott Hanselman posted a tip he found on Developer.com on how to set the default button to trigger when hitting the enter key on a web form:

Imagine you've created an ASP.NET Web page with a search button. The user taps a phrase into a text box and presses Enter. On most regular Web pages (think: Google), the form would be submitted and the results returned. In other words, the search button is automatically "clicked" for you.

However on an ASP.NET Web page, pressing Enter resubmits the form to the server, but actually does nothing... which is pretty useless, really.

So, how do you set a default button to be clicked when the user presses Enter? Simply add the following line to your page's Load event, replacing "btnSearch" with the name of your button. It uses a hidden Page method called RegisterHiddenField and works splendidly:

Page.RegisterHiddenField("__EVENTTARGET", "btnSearch")

 

There are also some more good ideas and reccomendations in the comments section.

Edit: Scott has posted a summary of the best suggestions and a new one from Dino Esposito.

Print | posted on Tuesday, August 31, 2004 6:51 AM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)
 
Please add 4 and 2 and type the answer here: