Scott Hanselman

ASP.NET: How to create a Default "Enter" Button for Forms/PostBacks

August 26, 2004 Comment on this post [16] Posted in ASP.NET
Sponsored By

Here's a useful gem...basically 'preloading' the __EVENTTARGET in a hidden form field - from Developer.com:

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")

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
August 26, 2004 2:09
Wouldn't you need the UniqueID (or ClientID, I can never keep them straight) instead of just the name? This would be especially true of a linkButton or other non-html form control.
August 26, 2004 2:58
The annoying this is that SOMETIMES you don't need it, sometimes you do. Sometimes the default action acts as you suspect, without this line of code. I never figured out what the situation is, but I suspect it has to do with the order controls are added to the page, or something equally confusing.

I haven't checked, but it'd be nice if the Page class in ASP.NET 2.0 had an AcceptButton property, analogous to the Form class in WinForms, that handled this for you. And now that I'm typing it, I might as well go suggest it at the Product Feedback Center.
August 26, 2004 7:06
Ok, I went ahead and submitted the suggestion.

Anyone that thinks an AcceptButton property would be a more obvious solution to this problem (or has alternate suggestions), please vote/comment here:
http://lab.msdn.microsoft.com/ProductFeedback/viewfeedback.aspx?feedbackid=c0f3cd76-65ed-436b-9477-3fe13155213a

(btw Scott, thanks for posting this. It will be a lot easier for me to find the correct syntax - I always find myself searching for it every 6 months)
August 26, 2004 16:39
To follow up with Marklio, you would use this (assuming btnSearch is the programmatic name of the button):

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

I had to do something similar in creating a default submit button per textbox in order to support multiple submit buttons on a single page (due to ASP.NET's limitation of only a single form). You can check out the code I posted here:
http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=a3b93959-9b2e-428a-99d9-276f0620589d
August 26, 2004 23:33
This won't work with more then one button within page scope. Routinely we are using multiple controls within a single page scope that may need the "enter" button "clicked" based upon where the user is coming from. As such our solution for this is the following:

Client-Side function:
function AnyInput_KeyDown (e, target)
{
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
{
__doPostBack(target, '');
return false;
}
return true;
}

Caller:
onkeydown -> "AnyInput_KeyDown(event,'btnSearch');"

:P
August 26, 2004 23:38
Furthermore, the JavaScript function for clicking a button will not work with an ImageButton in Netscape 7, because for some reason there is not a Click event on an image input tag in Netscape 7.

The only solution to this I have found is to add a hidden plain form button that replaces the ImageButton if Netscape 7 is detected during Page.Load.

What a huge pain.
August 26, 2004 23:39
I meant Click method, not Click event. ;-)
August 27, 2004 2:39
MetaBuilders free control: http://www.metabuilders.com/Tools/DefaultButtons.aspx works great.

Perfect for when you have multiple textboxes and the need for different buttons to be clicked depending upon which textbox you are in.
August 27, 2004 5:01
Scott we're on the same page again (btw I got the Image Resizing down to a science but have yet to post the code).

Anyway, I'm also trying to "think google" by setting focus to my searchbox OnLoad & by allowing me to hit Enter to submit my search.

I'm working on a search User Control that requires this behavior regardless of it's location on any page. Also, I don't want to modify the source code of any pages I drop the control into. I took the 2 solutions I found online and translated them over from C# to VB.Net (I had no choice in the matter, adopted a VB project but it's all good!).

My documentation & source code is here:
http://edsid.com/blog/archive/2004/08/26/211.aspx
August 27, 2004 21:54
If you have a one to one ratio between text boxes and buttons (one button for each text box - like in the case of a search string text box and a 'search' button) you can just hook into the TextChanged event on the text box. Doing so will cause the page to post back to the server when the user types something into the text box and presses enter. You could even cast the sender back to a TextBox (in your event handler) so that you could respond differently depending on what text box 'enter' was pressed on. This technique also works in Mozzila browers without modification.
August 28, 2004 12:53
I'd like to second James' comment above. Why not do it like that? Is there some bad-OOP-polymorphism-thing we're missing?

/*
... (map event handlers/delegates behind the magic VS.NET curtain)
*/

private void SearchBox_TextChanged(object sender, EventArgs e) {
// Pass the event along, as if it were a button click.
this.SearchButton_Click(sender, e);
}
August 30, 2004 7:44
I posted a similar fix for this quite a while back...

http://www.mattberther.com/2003/06/000125.html

My fix involves creating an invisible textbox control on the form, which may be more desirable than adding code to the code behind.

September 23, 2004 1:55
great post ! thank you.

This solution
Page.RegisterHiddenField("__EVENTTARGET", btnSearch.ClientId)

is not working with when there is another 'web usercontrol' exists on the same page. Is there any known issue ?
September 28, 2004 23:19
Hi. I have tried two of these solutions, RegisterHiddenField and TextBox Change event, but neither worked for my scenario. On my page I have 8 ImageButtons and 1 Textbox. 1 Imagebutton is used as the Search button. The other 7 buttons all redirect to a new page when the Command event fires.

The TextBox Change event sort of worked except that right after it fires, the ImageButton_Command event (which handles all 7 buttons) fires immediately afterwards. I tried a "work around" by setting a boolean flag in the Change event which gets checked in the Command event. The Command event then could bypass the Redirect code.

But this caused another problem. If I were to change the search text but decided not to search and instead clicked on one of the other ImageButtons, well the boolean flag gets set (obviously) and again the Redirect code is bypassed but this time I want the code to execute.

It seems no matter what I try, the ImageButton_Command event always fires when I hit the Enter key. I seem to have put myself in a Catch-22 situation and can't get out.

Being a newbie this is very frustrating. Can anyone offer suggestions.
Thanks
Bruce

June 23, 2005 3:57
On my site, I'm building a login page with a place for registered users to login and also for new users to click a button that links to a page to create their own login. I want it so that if a user inputs data into the form to login, and click enter, the Registered User button is "clicked", and that set of scripting runs. Right now, when I click Enter, it "clicks" the New Users button. Any ideas?
January 04, 2006 20:47
I know this post is quite old now, but I justed wanted to say that the following worked for me:

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

Using '.UniqueID' rather than '.ClientId'.
Thanks for this post, because its saved me quite a lot of JavaScript workarounds.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.