Wednesday, August 26, 2009

ASP.NET GridView Confirm Delete Button Field

Here is a quick and easy reusable "ConfirmButtonField" for use on an ASP.NET GridView

Just simply derive from ButtonField and override a couple things:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CreateSoftwareUtils.Web.GridViewControls
    public class ConfirmButtonField : ButtonField
        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
            base.InitializeCell(cell, cellType, rowState, rowIndex);
            if(cellType == DataControlCellType.DataCell)
                cell.Attributes.Add("onclick","return confirm(\"Are you sure?\");");
Then on the ASPX page you can do this:
        <cs:ConfirmButtonField ButtonType="Link"Text="Delete"CommandName="Delete"/>
        <asp:ButtonField ButtonType="Link"Text="View/Edit"CommandName="Select"/>
        <asp:BoundField DataField="Name"HeaderText="Title"HeaderStyle-Width="300px"ItemStyle-Width="300px"ItemStyle-Wrap="true"/>
        <asp:BoundField DataField="PriceDaily"HeaderText="Daily Rate"DataFormatString="{0:c}"HeaderStyle-Width="80px"/>
I also like to register controls I am going to use all over the site in the Web.Config like this:

<add tagPrefix="cs"namespace="CreateSoftwareUtils.Web.GridViewControls"assembly="CreateSoftwareUtils"/>


D said...

I don't see how this is implemented in a page.

I can't get it to work as a user control, and can't register a regular class as a user control.

Could you expand? Thanks.

D said...

OK, I figured that out: the .cs file had to be in App_Code, and only 'tagPrefix' and 'namespace' attributes should be used in web.config.

But the return value of the script is not passed to the page, so the delete cannot be cancelled.

m. said...
This comment has been removed by the author.