Confirmation should be handled at the client-side. Here's a quick example:
Suppose that you have this GridView Columns declaration:
<columns>
<asp:templatefield xmlns:asp="#unknown">
<HeaderTemplate>
<asp:button id="ButtonDelete" runat="server" text="Delete" />
</HeaderTemplate>
<itemtemplate>
<asp:checkbox id="CheckBox1" runat="server" />
</itemtemplate>
</asp:templatefield>
<asp:boundfield datafield="CustomerID" headertext="ID" readonly="True" xmlns:asp="#unknown" />
<asp:boundfield datafield="CompanyName" headertext="Company" xmlns:asp="#unknown" />
<asp:boundfield datafield="ContactName" headertext="Name" xmlns:asp="#unknown" />
<asp:boundfield datafield="ContactTitle" headertext="Title" xmlns:asp="#unknown" />
<asp:boundfield datafield="Address" headertext="Address" xmlns:asp="#unknown" />
<asp:boundfield datafield="Country" headertext="Country" xmlns:asp="#unknown" />
</columns>
You could then write a JavaScript function to handle the confirmation like in the following:
<script type="text/javascript" language="javascript">
function ConfirmOnDelete(item)
{
if(IsValidToDelete()){
if (confirm("The following item(s) will be deleted: " + item + "Continue?")==true)
return true;
else
return false;
}
else{
alert("Please check an item.");
}
}
function IsValidToDelete() {
var valid = false;
var gv = document.getElementById("<%=GridView1.ClientID%>");
for (var i = 0; i < gv.getElementsByTagName("input").length; i++) {
var node = gv.getElementsByTagName("input")[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
return valid;
}
</script>
Now, you need to hook up a JavaScript
onclick
event for the Delete button to invoke the
ConfirmOnDelete()
function. To to do that, you could do it like this at RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Button b = (Button)e.Row.FindControl("ButtonDelete");
b.Attributes.Add("onclick", "return ConfirmOnDelete();");
}
}
Or the simplest way is to directly call the
ConfirmOnDelete()
function declaratively like this:
<asp:button id="ButtonDelete" runat="server" text="Delete" xmlns:asp="#unknown">
OnClick="ButtonDelete_Click"
OnClientClick="return ConfirmOnDelete();" />
</asp:button>
Notice the call to
ConfirmOnDelete()
function in
OnClientClick
event.
For the server-side deletion, I would suggest you to refer this example:
GridView Multiple Delete with CheckBox and Confirm[
^]