Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction
Everyone likes a confirmation that lets them know that a record is being deleted. In
this article, I will show you how you can prompt confirmation boxes when you delete
a record from the GridView control.
The first thing that you need to do is to attach the JavaScript confirmation code to
the delete column of the GridView control. This can be done in the Row_DataBound
event of the GridView control. The Row_DataBound event is fired whenever the row
is attached to the GridView. Hence, this is fired when the GridView is building for
the first time or even when the page is reloaded.
As you can see from the above code, I have three columns in the GridView. Columns
CategoryID and CategoryName are the bound columns, and the column Delete is a
template column. The command argument is set as the CategoryID which means
that whenever the LinkButton is clicked, it will pass CategoryID as an argument.
The CommandName is set to "Delete".
Now, let's see the GridView_RowBound event where I attach the JavaScript code to
every LinkButton.
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record " +
DataBinder.Eval(e.Row.DataItem, "CategoryID") + "')");
}
}
In the above code, I checked whether the GridView row is a DataRow, and if it is, I
simply attach some JavaScript code using the Attributes.Add method.
Now that you have successfully attached the JavaScript code to the GridView
control, all that is left is to catch the primary key of the row which you have clicked
so that you can perform further operations (like deleting the row). Remember what I
said about a LinkButton or a Button control with the CommandName set to "Delete"?
If you don't, read the text in the box again.
Now, since our LinkButton's CommandName is set to "Delete", it means we have two
choices of getting the primary key from the GridView. We can do this in the
RowCommand event, or we can do this in the Row_Deleting event. I am going to show
you both of them.
This is pretty simple. All you need to do is to get the value from the
CommandArgument property which you have already set to the CategoryID.
Let's see how we can catch the primary key of the clicked row in the Row_Deleting
event.
In the above technique, you must set the DataKeyNames property of the GridView to
"CategoryID". The GridView1.DataKeys[e.RowIndex].Value property gets the
CategoryID out of the row which is clicked. I have attached the source code files
with this project so please feel free to download them.