views:

1859

answers:

3

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?

A: 

Use the TextChanged event, and set the AutoPostBack property to true.

chris
This fires off the event from just putting a character in there and clicking off the textbox, is there any way to prevent that?
Shahin
Not really. TextChanged will be fired when you hit return in the text box, or when the text box loses focus. (Assuming the text has actually changed.) Sorry, but it's just the way it works. Otherwise, you would need to use javascript and handle it all yourself.
chris
+2  A: 

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.

bdukes
+2  A: 

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.

Max Schilling
In my experience, the DefaultButton property doesn't work outside of IE
bdukes
Upon further investigation, that may just be when the button is a LinkButton that it doesn't work outside IE...
bdukes
hmm... I never knew about that limitation for linkbutton... Thanks!Good article here describing it and a workaround for it: http://kpumuk.info/asp-net/using-panel-defaultbutton-property-with-linkbutton-control-in-asp-net/
Max Schilling
In my experience, it works well across browsers for buttons.
Stefan