ASP.Net, Ajax.Net, C#, VB.NET, MS SQL Server, Oracle, JavaScript, JQuery
Today's Date: 5/22/2013

Delete Functionality in GridView with Confirmation using JQuery UI Dialog

Technologies Used: ASP.NET 4.0, JQuery, MS SQL Server, C#, VB.NET

The Problem:

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 also want to show a dialog to the user when an error occurs during deletion.

The Solution:

Minor Details: This example uses the (Microsoft) Northwind databases'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 the stored procedure. You don't have to use an ObjectDataSource control to delete an item in your data source, you could also a SQLDataSource, etc.

1. Initialize the JQuery UI Dialog plugin.

$(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");
            }
        }
    });
}

2. 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 ProductID 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.


Delete confirmation dialog box


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 ProductID (CommandArgument='<%# Eval("ProductID") %>') value to the ObjectDataSource control.


3. 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); 
}


4. After the ObjectDataSource calls the DeletedMethod, the ondeleted event fires. We can check for any errors here during item deletion. Code snippets 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)
    {
        // show delete error
        string errorMessage = Functions.RemoveSpecialChars(e.Exception.InnerException.Message);
        ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg""ShowError('" + errorMessage + "');"true);
        e.ExceptionHandled = true;
    }
}

private static string RemoveSpecialChars(string text)
{
    Regex regex = new Regex("[^a-zA-Z0-9 -]");
    return regex.Replace(text, "");
}

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 don't break.

function ShowError(errorMessage) {
    $(document).ready(function () {
        $("#deleteErrorDialog").html(errorMessage);
        $("#deleteErrorDialog").dialog({
            modal: true,
            buttons: {
                Ok: function () {
                    $(this).dialog("close");
                }
            }
        });
    });
}


Delete error


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.

Code Download: Download the code in C#, Download the code in VB.NET


Demonstration: 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.

Questions, comments: junnark@gmail.com

Happy Coding!!!

Date Created: Thursday, July 28, 2011