Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Attach JavaScript with Auto-Generated Buttons of the GridView Control

0.00/5 (No votes)
7 Feb 2013CPOL1 min read 16.9K  
Attach JavaScript with auto-generated buttons of the GridView control.

This small post is about how you can attach a JavaScript confirm box with the auto-generated Delete button of the GridView control in ASP.NET. This might be an old trick but is helpful to beginner developers.

Consider the following ASPX grid code:

XML
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="true"
   AutoGenerateColumns="false" AutoGenerateEditButton="True" 
   onrowcancelingedit="GridView1_RowCancelingEdit" 
   onrowdeleting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
   onrowdatabound="GridView1_RowDataBound"
   <Columns>
    <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
    <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
    <asp:BoundField DataField="LastName" HeaderText="LastName" />
    <asp:BoundField DataField="Address" HeaderText="Address" />
   </Columns>>
</asp:GridView>

As you can see in the above code, AutoGenerateDeleteButton="true" means in the grid you can see a delete button to remove the record from the grid. But the requirement is I have to ask the user whether he wants to delete the record or not.

So to achieve this I made use of the RowDataBound event and the JavaScript function confirm which asks the user whether to delete a record or not, if the user presses yes then page gets a postback and it removes the record from the grid and marks it as deleted in the database.

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
     if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState ==
                                            DataControlRowState.Alternate)
     {
         ((LinkButton)e.Row.Cells[0].Controls[2]).Attributes["onclick"] = 
               "if(!confirm('Are you sure to delete this row?'))return   false;";
     }
   }
}

As you can see in the above code I am searching for the deletelinkbutton and attaching an OnClick event of JavaScript with the control number 2 of the cell 0. Because auto-generated buttons are always placed in cell 0 of the grid and here as you can see in the code, the edit button is also auto generated which gets placed first in cell 0 of the grid so the auto-generated delete button gets placed 2 in cell 0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)