views:

440

answers:

6

In ASP.net Webforms how do you detect which Textbox someone pressed enter?

Please no Javascript answers.

I need to handle it all in the code behind using VB.NET.

+2  A: 

I suspect it cannot be done without javascript - when you hit enter, the browser submits the form - it doesn't submit what field had the focus. So unless you use JS to add that information to the form being submitted, you're out of luck.

zigdon
+1  A: 

Without using Javascript, you just can't. That information is not conveyed from the client browser to the server.

Forgotten Semicolon
+1  A: 

As far as I know there is no possible way for a server side script to detect that. It simply does not get sent to the server. It must be done client-side (i.e. With Javascript) and then sent to the server.

HappySmileMan
+1  A: 

Why do you need to determine the which TextBox was pressed? Are you looking to see which TextBox was being focused so that you can trigger the proper button click event?

If you are looking to do something like this, one trick I've done was to "group" the appropriate form elements within their own panel and then set the "DefaultButton" property accordingly.

Doing this allows me to have a "Search by Name", "Search by Department", "Search by Id", etc. Textbox/Button combination on a single form and still allow the user to type their query parameter, hit Enter, and have the proper search method get invoked in the code behind.

Dillie-O
problem is I have three fields and two buttons. username/password, and search. each needs separate validation and the default action should be intuitive. i've spent a lot of time today on this and I can't believe how hard this is to do using WebForms...
Brian Boatright
+1  A: 

I solved this for one site's search by looking at the Request.Form object, server side to see if the search box had a value. I did it in a base class that all my pages (or a base class for the masterpage) inherit from. If it has a value, the odds are pretty good somebody typed something in and hit enter and so I handled the search.

typemismatch
Yea. That's what I'm doing but now the validation for the username/password is being launched by the search button as well. I'm using ValidationGroup but it's not working.
Brian Boatright
+1  A: 

In the event handler, the "source" object (the first parameter of the event handler) is the object raising the event. Type it to button and get the name, or use reflection to get information out of the non-typed object.

In addition, if the control is a child of a web control that you do not have raise its own events (just saying...) then you can use OnBubbleEvent to determine what's going on. OnBubbleEvent also has a "source" parameter you can type, or use reflection on.

nathaniel