Over a million developers have joined DZone.

Attach JavaScript scripts to auto-generated buttons in the ASP.NET GridView

This small post shows how you can attach a JavaScript confirmation message to the the auto-generated "Delete" button in the ASP.NET GridView control. This might be an old trick, but it might be helpful for beginner developers.

Consider the following .ASPX grid code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="true"
   AutoGenerateColumns="false" AutoGenerateEditButton="True" 
   onrowdeleting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
    <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
    <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
    <asp:BoundField DataField="LastName" HeaderText="LastName" />
    <asp:BoundField DataField="Address" HeaderText="Address" />
Now as you can see in the above snippet, AutoGenerateDeleteButton="true" is true, which means that you can now see a button to delete a record directly from the grid. However, it would be great to ask the user whether he wants to delete the record or not.

To achieve this, I used the RowDataBound event handler coupled with the confirm JavaScript function, that asks the user if he really wants to delete the selected item. If the user presses "yes", the page will get a postback and the record will be removed from the grid, also marked as deleted in my database.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  if (e.Row.RowType == DataControlRowType.DataRow)
     if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState ==
            ((LinkButton)e.Row.Cells[0].Controls[2]).Attributes["onclick"] = 
                  "if(!confirm('Are you sure to delete this row?'))return   false;";
Now as you can see in above code I am searching for the deletelinkbutton and attaching the JavaScript OnClick event with the control No.2 (Cell 0) - because auto-generated buttons are always placed in the "zero cell".

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}