GridView, I know..., but none of them were exactly what I was after. My method can be used when Updates and Deletes are automatically handled by an
asp:LinqDataSource control. You will need your own LINQ
DataContext class for your database, and I guess the same principle can be applied to other data source classes too.
First, you will need a
GridView control that gets its data from a
LinqDataSource. Make sure you specify the
OnRowDataBound attribute and use the
LinqDataSource with delete enabled.
<asp:GridView ID="GridView1" runat="server" PageSize="10" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="RecordID"
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code"
<asp:BoundField DataField="Description" HeaderText="Description"
<asp:CommandField HeaderImageUrl="..\Images\DeleteImg.png" ShowDeleteButton="True"
DeleteImageUrl="..\Images\DeleteImg.png" DeleteText="Delete Record"
ItemStyle-Font-Size="8pt" ItemStyle-Width="30px" ButtonType="Image">
<asp:LinqDataSource ID="MyDataSource" runat="server"
EnableUpdate="true" EnableDelete="true" TableName="MyTable">
Except for the
OnRowDataBound, this control should now work with delete functionality without writing a single line of code.
The next step is to implement the
GridView_RowDataBound function which looks like this:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
foreach (DataControlFieldCell cell in e.Row.Cells)
foreach (Control control in cell.Controls)
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
The important bit here is to use exactly the
OnClientClick content provided (except the wording in the message, of course). If you, for example, instead, had
"return confirm('Are you sure you want to delete the record')" like many others have suggested, this would mean the Delete command would never be posted back to the server. The actual
onclick function call generated/rendered by ASP.NET - if you follow the code supplied above - will be something like this...
onclick="if (!confirm('Are you sure you want to delete this record?')) return;
Note: I used images for my command buttons in my
GridView. Remember to cast to the
LinkButton class instead of the
ImageButton class if you use text-links for command buttons.