How to handle enter on button in Gridview

Good Morning,

I have this : onkeydown="if ((event.which && event.which == 13) ||
    (event.keyCode && event.keyCode == 13))
    {;return false;}
    else return true;"

in a usercontrol to handle enter and it works perfect.  I want to  add the above in the codebehind of a gridview that dynamically adds a button  onrowbound to every row.  I know how to add the above using attributes.add.  What I need help with is how to figure out what the name of the button is on each row?  

Bottom line is I need to handle enter for each row in this gridview.    Thanks.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kiran SonawaneProject LeadCommented:
Add like this

btn.Attributes.Add("onkeyup","if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)){;return false;}  else return true;");
Carlos VillegasFull Stack .NET DeveloperCommented:
Hello, I think that you need something like this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    Button btn = new Button();
    e.Row.Cells[1].Controls.Add(btn);//First add the button, then you can have its id by using the ClientID property.
    btn.Text = "My Button";
    e.Row.Attributes.Add("onkeydown", "if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {document.getElementById('" + btn.ClientID + "').click();return false;} else return true;");

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
thamilto0410Author Commented:
yv989c: That worked like a charm.  Thanks so much.  One more question.  If I were going to pass the clicked record to an update procedure.  How do I get each of the buttons to call the same procedure and pass the record data back to it?  
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Carlos VillegasFull Stack .NET DeveloperCommented:
Hello, I dont know exactly what you are doing, but handling an event from a dynamically created control inside a GridView is more complicated, especially if you want to attach a piece of data of the GridView row that contain it, why you not use just a template?, see the next example, I'm using a template and handling the enter key as you want:
<%@ Import Namespace="System.Data" %>

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            // Sample data...
            DataTable dtt = new DataTable();
            dtt.Columns.Add("ColumnA", typeof(int));
            GridView1.DataSource = dtt;

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        if (e.CommandName == "Save")
            Button myButton = (Button)e.CommandSource;
            GridViewRow myRow = (GridViewRow)myButton.NamingContainer;

            TextBox myTextBox = (TextBox)myRow.FindControl("MyTextBox");
            int myKey = (int)GridView1.DataKeys[myRow.DataItemIndex]["ColumnA"];

            // Here you can save your values to a DB
            Response.Write("Key: " + myKey + "<br/>Text: " + myTextBox.Text + "<br/>");

    protected override void Render(HtmlTextWriter writer)
        foreach (GridViewRow row in GridView1.Rows)
            row.Attributes.Add("onkeydown", "saveRecord('" + row.FindControl("MyButton").ClientID + "');");

<html xmlns="">
<head runat="server">
    <script type="text/javascript">
        function saveRecord(controlId) {
            if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ColumnA"
            <asp:TemplateField HeaderText="My Column">
                    <asp:TextBox runat="server" ID="MyTextBox" />
                    <asp:Button runat="server" ID="MyButton" Text="Save" CommandName="Save" UseSubmitBehavior="false" />

Open in new window

Here the full aspx page:

I hope this helps.
thamilto0410Author Commented:
yv989c: I have a gridview that displays data and allows a note to be added to the record with a textbox and a button.  The button click event works fine but I wanted to handle the button as if the enter key was used instead.  I don't think I can use the above as my gridview is built completely at run time.
thamilto0410Author Commented:
yv989c: Never mind I figured it out using rowcommand.  You answered my question on how to name the button.  Thanks so much.
thamilto0410Author Commented:
I learned something new.  Thanks so much.
Carlos VillegasFull Stack .NET DeveloperCommented:
Glad to have been of help
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.