Search code examples
asp.nettextboxkeyentertextchanged

How to detect postback caused by enter key in textbox in ASP.NET


A TextBox in a web application will cause a TextChanged event when Enter is pressed, but only if the text has changed.

If the text has not changed when Enter is pressed, a postback still occurs, but the TextChanged event does not.

I'm wondering if it is possible to determine that Enter was pressed in a textbox and caused the postback, ie. is there something like the following?

protected void Page_Load(object sender, EventArgs e) {
    if (sender.reasonControlName == "MyTextBox" &&
            sender.reasonControlKey == keyEnter) {
        handleEnterKey();
    }
}

ASP.Net 4

Note, this is not a question about how to disable the postback caused by ENTER key in a TextBox in a web application, e.g. stackoverflow.com/questions/4209903

There is also a workaround using a panel and DefaultButton stackoverflow.com/questions/12072281, but this seems like a bit of a cludge.


Solution

  • The ID of the TextBox where Enter was pressed can be stored in a hidden field:

    <asp:TextBox ID="txtBox1" runat="server" onkeydown="keyPressed(event, 'txtBox1');" ... />
    <asp:TextBox ID="txtBox2" runat="server" onkeydown="keyPressed(event, 'txtBox2');" ... />
    <asp:HiddenField ID="hiddenEnterPressed" runat="server" />
    
    <script>
        function keyPressed(e, id) {
            if (e.keyCode == 13) {
                document.getElementById('hiddenEnterPressed').value = id;
            }
        }
    </script>
    

    Note: The onkeydown event could be defined as keyPressed(event, this.id) but the (possibly) mangled ID would then be saved in the hidden field; hard-coding the original ID can make things simpler.

    The TextBox control can be retrieved in code-behind:

    Control mainCtrl = Master.FindControl("MainContent");
    TextBox txtBox = mainCtrl.FindControl(hiddenEnterPressed.Value) as TextBox;
    

    The hidden field should be reset on each postback:

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        hiddenEnterPressed.Value = "";
    }