Introduction
You're using a GridView
web control to list records from a particular data source and you want a delete functionality for each row of data. A dialog must
be presented to the user to confirm deletion. There's also a possibility of error when deleting a record from your data source and you want to show a dialog
to the user when an error occurs during deletion.
The Solution
Minor details: This example uses the (Microsoft) Northwind database's Product table. The GridView
web control gets the data via an ObjectDataSource
web control.
The ObjectDataSource
gets the data (SelectMethod
) through a strongly-typed middle-tier object which encapsulates a data-tier object that calls on
a Stored Procedure. You don't have to use an ObjectDataSource
control to delete an item in your data source, you could also use a SQLDataSource
, etc.
- Initialize the jQuery UI Dialog plug-in.
$(function () {
InitializeDeleteConfirmation();
});
function InitializeDeleteConfirmation() {
$('#deleteConfirmationDialog').dialog({
autoOpen: false,
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
- Add a
TemplateField
in the GridView
. Inside the template field, add an ImageButton
.
<asp:TemplateField>
<ItemStyle Width="30px" HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="IBtnDelete" runat="server" ToolTip="Click to delete"
CommandArgument='<%# Eval("ProductID") %>'
OnClientClick="javascript:return deleteItem(this.name, this.alt);"
ImageUrl="~/Images/Delete.png" AlternateText='<%# Eval("ProductID") %>'
CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
The code above passes the product ID via the ImageButton
's AlternateText
property. When the button is clicked, it will call a client-side
JavaScript function called deleteItem
. The deleteItem
function shows the dialog box to the user. See snapshot and code below.
function deleteItem(uniqueID, itemID) {
var dialogTitle = 'Permanently Delete Item ' + itemID + '?';
$("#deleteConfirmationDialog").html('<p><span class="ui-icon " +
"ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>" +
"Please click delete to confirm deletion.</p>');
$("#deleteConfirmationDialog").dialog({
title: dialogTitle,
buttons: {
"Delete": function () { __doPostBack(uniqueID, '');
$(this).dialog("close"); },
"Cancel": function () { $(this).dialog("close"); }
}
});
$('#deleteConfirmationDialog').dialog('open');
return false;
}
When the delete button in the dialog is clicked, a postback is performed and then the dialog box is closed. Otherwise the dialog is just closed without further actions.
When post back occurs by clicking the delete ImageButton
, the GridView
sends a Delete command (CommandName="Delete"
) along with
the product ID (CommandArgument='<%# Eval("ProductID") %>'
) value to the ObjectDataSource
control.
- The
ObjectDataSource
will look for a static method (C#) (shared function in VB.NET) called Delete
that takes a parameter called ProductID
.
The function or method is located in the Northwind.BusinessObject.Products
object. This will delete the specific record.
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="Northwind.BusinessObject.Products"
SelectMethod="SelectAll" SortParameterName="sortExpression"
DeleteMethod="Delete" ondeleted="ObjectDataSource1_Deleted">
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
Here's a sample Delete
function:
public static void Delete(int productID)
{
ProductsDataLayer.Delete(productID);
}
- After the
ObjectDataSource
calls the Deleted
method, the ondeleted
event fires. We can check for any errors here during item deletion.
Code snippets are shown below.
protected void ObjectDataSource1_Deleted(object sender,
System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs e)
{
Functions.ObjectDataSourceDeleted(sender, e, this.Page);
}
public static void ObjectDataSourceDeleted(object sender,
System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs e, Page page)
{
if (e.Exception != null)
{
string errorMessage =
Functions.RemoveSpecialChars(e.Exception.InnerException.Message);
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg",
"ShowError('" + errorMessage + "');", true);
e.ExceptionHandled = true;
}
}
When an error occurs, we call a JavaScript function called ShowError
passing the errorMessage
. See snapshot below. Note: We remove special characters
so that our client-side script won't break.
function ShowError(errorMessage) {
$(document).ready(function () {
$("#deleteErrorDialog").html(errorMessage);
$("#deleteErrorDialog").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
});
}
Last Words
To run the code download, make sure to download and install Microsoft's Northwind database. Also make sure to change the user name and password
on the Dbase.cs (Dbase.vb) class file found in the App_Code folder, under the Helper folder. The code for download is a modified version of the generated
web form by AspxFormsGen 4.0.
The original article can be found here.
Demo
Click here to see the demo.
As always, the code and the article are provided "As Is", there is absolutely no warranties. Use at your own risk.
Happy coding!!!