Preferred Language:

Listing 11.33 - DeleteButtonField.cs

Illustrates how to create a custom GridView field that displays a delete button.

Listing 11.33 - DeleteButtonField.cs (C#)
Copy

using System;
using System.Web.UI.WebControls;

namespace myControls
{
    /// <summary>
    /// Displays a confirmation before deleting a record
    /// </summary>
    public class DeleteButtonField : ButtonField
    {
        private string _confirmText = "Delete this record?";

        public string ConfirmText
        {
            get { return _confirmText; }
            set { _confirmText = value; }
        }

        public DeleteButtonField()
        {
            this.CommandName = "Delete";
            this.Text = "Delete";
        }

        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            base.InitializeCell(cell, cellType, rowState, rowIndex);
            if (cellType == DataControlCellType.DataCell)
            {
                WebControl button = (WebControl)cell.Controls[0];
                button.Attributes["onclick"] = String.Format("return confirm('{0}');", _confirmText);
            }
        }

    }
}

The following GridView uses the custom DeleteButtonField field.

Listing 11.34 - ShowDeleteButtonField.aspx (C#)
Copy

<%@ Page Language="C#" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        .grid td, .grid th
        {
            padding:5px;
        }
    </style>
    <title>Show DeleteButtonField</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView
        id="grdMovies"
        CssClass="grid"
        DataSourceID="srcMovies"
        DataKeyNames="Id"
        AutoGenerateColumns="false"
        Runat="server">
        <Columns>
        <custom:DeleteButtonField
            ConfirmText="Are you sure that you want to delete this record?" />            
        <asp:BoundField
            DataField="Title"
            HeaderText="Movie Title" />
        <asp:BoundField
            DataField="Director"
            HeaderText="Movie Director" />
        </Columns>
    </asp:GridView>    

    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:Movies %>"
        SelectCommand="SELECT Id, Title, Director FROM Movies"
        DeleteCommand="DELETE Movies WHERE Id=@Id"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>