Preferred Language:
Listing 11.33 - DeleteButtonField.cs
Illustrates how to create a custom GridView field that displays a delete button.
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.
<%@ 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>
ASP.NET 3.5 Unleashed
- Containing almost 2,000 pages of code samples and in-depth explanation of the
ASP.NET 3.5 Framework, ASP.NET 3.5 Unleashed is the most comprehensive book
written on the ASP.NET 3.5 Framework.
ASP.NET 3.5 Unleashed is now available in your local bookstore and online (Published January 7, 2008).
All of the code samples from this book are hosted "live" at this website.
Click here
to view the table of contents and code samples.