Back to all posts

Trigger a Specific ASP.NET WebForms Control To Postback

Posted on Apr 18, 2011

Posted in category:
Development
ASP.NET

I was recently debugging an issue with a form where the user wanted the "enter" button when pressed in a textbox to trigger a specific ASP.NET button to post back to the server. I have done similar things in the past with a method that changes for the pressing of Character 13 which is the enter key, then finding the button by id and then continuing on. Well, recently I found out that depending on the structure you can still get some "interesting" results. So I went looking for a different method and came up with the following.

Keypress Event Code
<script type="text/javascript">
function checkEnterSearch(e) {
    var characterCode;
    e = event;
    characterCode = e.keyCode;
    if (characterCode == 13) { 
        //Action Goes Here
        <%= Page.ClientScript.GetPostBackEventReference(YourControl, "") %>
        return false;
    }
    else{
        return true;
    }
}

With this script block in your code, you can simply make two modifications. Replace the "YourControl" piece with the server-side name of your target control, and then add the following attribute definition to all textboxes that you want to have this behavior.

Addition to Trigger Control
onkeypress="return checkEnterSearch(event);"

This route uses the server-side operation "GetPostBackEventReference" which returns essentially a fully executable line of JavaScript that will trigger a postback with the defined target control.

I hope this helps, feel free to share comments/questions below.