How to: Check for Enter/Return inside a textbox (server-side binding)

Working with textboxes on a page, you may find yourself wanting to submit the data as soon as the Enter/Return key is pressed.

In order to achieve that, you need to bind the event in the OnPreRender method. If your textbox is “txtKeyword”, do the following:

protected override void OnPreRender (EventArgs e)
{
string defaultButtonScript = “if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById(‘” + searchButtonClientId + “‘).click();return false;}} else {return true}; “;
txtKeyword.Attibutes.Add(“onkeydown”, defaultButtonScript);
}

Explanation: what happens here is that you’re binding a server side control’s event to a client side event. In effect, you’re binding the Enter key (that will be pressed while inside the txtKeyword textbox) to the Click() event of the searchButton (assuming there’s a searchButton ASP.NET button on the page). What will happen then is that as soon as a user hits the Enter key, while inside the txtKeyword textbox, the code that runs when the searchButton is being clicked will be executed.

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.