ASP.Net C# Gridview Delete Confirmation When Using a CommandField

July 28, 2011

I’m working on a Gridview and ran into an issue where I couldn’t use a templatefield for my Delete link and I needed a Delete Confirmation. Looking on Google the most widely used option is to simply use a templatefield.¬†Finally after 2 days of looking I found a reference for adding the Delete confirmation on a Microsoft MSDN tutorial.

You can find the page here with the referrence in Step 3.

In order to pull this off you will have to add a OnRowDataBound referrence to you GridView.¬† I added OnRowDataBound=”UserGrid_RowDataBound” to my GridView tag. Then added the following in the code behind.

protected void UserGrid_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
// reference the Delete LinkButton in cell 0 and control 2
LinkButton db = (LinkButton)e.Row.Cells[0].Controls[2];

// Get information about the product bound to the row
string UserName = e.Row.Cells[2].Text;
db.OnClientClick = string.Format(“return confirm(‘Are you certain you want to delete User {0}? You risk a severe beating if you mess up!’);”, UserName);

Since I’m using both the edit and the delete features of the CommandField I had to specify Controls[2] as the delete link. Otherwise if you only have the delete link you could specify Controls[0].

Also I wanted to show the username of the item being deleted. So I got the username from e.Row.Cells[2].Text. And then in the confirmation message I did a string.Format to replace {0} with the username.

And that’s it. Now when someone clicks to delete the confirmation message pops up. I hope this helps someone.

Got something to say?

You must be logged in to post a comment.