Thursday, February 25, 2010

ASP.NET C# OnEnter event in TextBox

Here is a workaround for ASP.NET C# if you want an event that triggers on pressing the "Enter" key on your keyboard while still inside a textbox.

First the javascript snippet:

if (event.which || event.keyCode) {
    if ((event.which == 13) || (event.keyCode == 13)) {
        return false;

else {
    return true;

It just captures the "Enter" key press (which is 13) and then clicks the corresponding button to trigger its event. So you just place this script on the textbox's onkeydown attribute which I'll show in just a sec.

protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
        txtBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnClick.UniqueID + "').click();return false;}} else {return true}; ");

Just add the attribute on the Page_Load event and you're done.

Check this link for more keycodes:


1 comment: