views:

25

answers:

3

Hi, I have a usercontrol which is used for searching. There is a textbox and a search button. When the button is clicked the search method is called. I want the search also to occur when the cursor is inside the textbox and the enter key is pressed.

My first thought on how to do this was maybe to add the event to submit action of the form tag. However this usercontrol has no form tag.

Does anyone have any suggestions?

Thanks!

A: 

By default, if a user clicks Enter while in a textbox, the form is posted, triggering a postback. Therefore:

Make this happen in the ontextchanged event. Here's about the easiest code sample ever written:

 <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

and in code-behind:

protected void Button1_Click(object sender, EventArgs e)
{
    SomeFunctionForHandlingEvents();
}
 protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    SomeFunctionForHandlingEvents();
}
private void SomeFunctionForHandlingEvents()
{
     Label1.Text = "event called";
}
David Stratton
Isn't Text_Changed called during a postback, which would require some submit action to be taken client-side?
KeithS
Sorry, I didn't see a requirement for no postback. However, clicking "Enter" while in a textbox will submit the form, triggering a postback. If you want the illision of no postback, you'll need to include Ajax in your solution.
David Stratton
Of course, this won't work if the TextBox is set to Multiline
David Stratton
+1  A: 

I would do it using JavaScript: attach an OnKeyPress handler that looks for key code 13, and calls form.submit:

function enterPressed(evn) {
if (window.event && window.event.keyCode == 13) {
  document.forms[0].submit;
} else if (evn && evn.keyCode == 13) {
  document.forms[0].submit;
}
}
document.onkeypress = enterPressed;
KeithS
This would be perfect for a Multiline textbox, so +1, but it's not necessary for a normal ASP:Textbox or even an html input. Hitting Enter in a textbox will trigger a postback unless he has specifically overridden that behavior.
David Stratton
A: 

Are you running on a web page or locally? Hitting Enter in a textbox usually moves you to the next field locally so you could use the OnLeave event (I think that's its name). On a web page Enter will usually submit the form which is exactly what you want. Grab the new value from the TextChanged event.

verisimilidude
No... Hitting Enter usually submits the form. Hitting TAB usually moves to the next field.
David Stratton