Click here to Skip to main content
Licence CPOL
First Posted 5 Sep 2007
Views 71,208
Downloads 698
Bookmarked 57 times

Extending the GridView CommandField To Add Delete Confirmation

By | 5 Sep 2007 | Article
Tired of constantly writing the same labourious plumbing to add a confirmation to a delete button in a GridView? I was, so I simplified things.
Screenshot - ExtendedCommandField.gif

Introduction

We've all added delete confirmations before; they're a really great way of stopping users from doing something they didn't intend with disastrous consequences. Sadly the GridView's CommandField doesn't natively support this, requiring lots of boring plumbing to be duplicated in code-behind files. This article describes a simple, clean and reusable method of adding a delete confirmation by extending the CommandField control.

Background

This article roughly follows on from my previous article on extending the GridView control and illustrates in a similar manner, the advantage of extending existing controls to provide additional functionality.

About the Code

The sample project contains a demo form and the key class ExtendedCommandField. It simply inherits from the standard CommandField class and provides a new property, DeleteConfirmationText, that allows you to set the text that will appear in the confirmation box. If no text is supplied, the field behaves like a standard CommandField and provides no delete confirmation. When the property is set, the usual basic JavaScript to display the confirmation box is added to the delete button.

This is all done in the InitializeCell method where you can perform all sorts of tricks to further customize the appearance and behaviour of the field.

/// <summary>
/// An extended <see cref="CommandField"/> that allows deletions
/// to be confirmed by the user.
/// </summary>
public class ExtendedCommandField : CommandField
{
    /// <summary>
    /// Initialize the cell.
    /// </summary>
    public override void InitializeCell(DataControlFieldCell cell, 
        DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
    {
        base.InitializeCell(cell, cellType, rowState, rowIndex);
        if (!string.IsNullOrEmpty(this.DeleteConfirmationText) && this.ShowDeleteButton)
        {
            foreach (Control control in cell.Controls)
            {
                IButtonControl button = control as IButtonControl;
                if (button != null && button.CommandName == "Delete")
                    // Add delete confirmation
                    ((WebControl)control).Attributes.Add("onclick", string.Format
                    ("if (!confirm('{0}')) return false;", this.DeleteConfirmationText));
            }
        }
    }

    #region DeleteConfirmationText
    /// <summary>
    /// Delete confirmation text.
    /// </summary>
    [Category("Behavior")]
    [Description("The text shown to the user to confirm the deletion.")]
    public string DeleteConfirmationText
    {
        get { return this.ViewState["DeleteConfirmationText"] as string; }
        set { this.ViewState["DeleteConfirmationText"] = value; }
    }
    #endregion
}

Using the Code

You can then use the ExtendedCommandField in your GridView just as you would a normal column.

<asp:GridView ID="grid" runat="server">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="StockLevel" HeaderText="Stock Level" />
        <Alex:ExtendedCommandField DeleteConfirmationText=
            "Are you sure you want to remove this item?" 
            HeaderText="Action" ShowDeleteButton="True" />
    </Columns>
</asp:GridView> 

Don't forget, of course, that you'll need a @Register directive at the top of the page so ASP.NET knows where to find the control.

Points of Interest

The InitializeCell method is a convenient way to customize the behaviour and appearance of GridView fields. More generally, one could easily extend the DataControlField to provide completely custom behaviour. One such extension I intend to develop soon is a DropDownListField which allows users to select values from a DropDownList within a GridView cell.

History

  • 06-Sep-07: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alex Furmanski

Web Developer

United Kingdom United Kingdom

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralProblem: "Error Creating Control" PinmemberMember 474288823:45 10 Jun '10  
GeneralThanks! PinmemberBiff_MaGriff11:37 2 Jun '10  
GeneralGood idea PinmemberDonsw9:44 13 Apr '09  
GeneralJust great Pinmemberldelvasto5:36 3 Feb '09  
QuestionUser or Server Control? Pinmemberorganicglenn11:57 22 Dec '08  
GeneralDesigner problem Pinmembermiguel.hughes7:57 19 Nov '08  
QuestionHow to disable DeleteButton? [modified] Pinmemberqwedster19:18 23 Oct '08  
QuestionQuick Question... PinmemberJMirando2:12 28 Sep '08  
GeneralExcellent PinmemberLeblanc Meneses19:45 20 Mar '08  
GeneralSuperb! PinmemberJayAdair13:17 14 Mar '08  
GeneralThanks a lot!! PinmemberHacheka23:00 21 Feb '08  
I owe you one Wink | ;)
GeneralProps and Question Pinmemberinetfly1239:42 21 Feb '08  
GeneralRe: Props and Question PinmemberAlex Furmanski0:16 22 Feb '08  
GeneralThanks saved me tons of time on this Pinmembercodegalaxy4:53 16 Nov '07  
QuestionTemplateField? Pinmembertmbgfan3:55 7 Sep '07  
AnswerRe: TemplateField? PinmemberAlex Furmanski9:27 7 Sep '07  
GeneralRe: TemplateField? PinmemberLarry Daniele10:15 31 Oct '08  
GeneralUsefull PinmemberNinjaCross5:05 6 Sep '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 5 Sep 2007
Article Copyright 2007 by Alex Furmanski
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid