ASPX Textbox: Execute method on return keypress
Question
I have a search box that doesn't have a submit button, I need to be able to hit enter and then execute a method, how do I do this?
Solution
you could also do something simple like this with CSS:
<asp:Panel DefaultButton="myButton" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
<asp:Button ID="myButton" runat="server" onclick="myButton_Click" style="display: none; " />
</asp:Panel>
The panel may or may not be necessary depending on your implementation and surrounding controls, but this works and does a postback for me.
OTHER TIPS
You could add a hidden button to the page and wire-up your method to that button's click event. Then add a small bit of javascript to trigger that button's postback action when you press enter inside the textbox.
this.myTextBox.Attributes.Add(
"onkeydown",
"return keyDownHandler(13, 'javascript:"
+ this.Page.ClientScript.GetPostBackEventReference(this.myButton, string.Empty).Replace("'", "%27")
+ "', event);");
(You could also replace the hard-coded 13 with Windows.Forms.Keys.Enter, if you'd prefer an easier to read version.)
Where keyDownHandler is a JavaScript function like this:
function keyDownHandler(iKeyCode, sFunc, e) {
if (e == null) {
e = window.event;
}
if (e.keyCode == iKeyCode) {
eval(unescape(sFunc)); return false;
}
}
Note, this is based on the implementation of DotNetNuke's ClientAPI web utility.
Use the TextChanged event, and set the AutoPostBack property to true.