Tuesday 17 October 2017

How to trigger button click event when Enter key pressed in Textbox?

In this post, I will explain How to trigger button click event when Enter key pressed in Textbox?.

To trigger the Button click event when user press Enter Key in Textbox, I have used JavaScript function call with Textbox "onkeypress" event. There is no server-side keypress event for an ASP.Net Textbox. When the user presses any key, JavaScript function check whether it is an Enter key with the help of char code. If pressed key is Enter key then JavaScript function triggers an Asp.Net Button click event. Please go through below code for details.


<%@ Page Language = "C#" AutoEventWireup = "true" CodeBehind = "TriggerButtonClickEvent.aspx.cs" Inherits = "TestApplication.TriggerButtonClickEvent"  %>

<!DOCTYPE html>

    <title> How to trigger button click event when Enter key pressed in textbox? </title>

    <script type="text/javascript" language="javascript">

        function TriggerButtonClick(obj, event) {
            var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
            if (keyCode == 13) {
                return false;
            else {
                return true;
    <form id="form1" runat="server">

        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

        <asp:Button ID="btnSubmit" runat="server" OnClick = "Button1_Click" />

C#.Net Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestApplication
    public partial class TriggerButtonClickEvent : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            txtName.Attributes.Add("onkeypress", "return TriggerButtonClick('" + btnSubmit.ClientID + "', event)");

        protected void btnSubmit_Click(object sender, EventArgs e)
            Response.Write("Button click event triggered!");


Post a Comment

Please do not enter any spam link in the message box.