How to Confirm a Delete in an ASP.NET Datagrid...

原创 2004年10月06日 21:00:00

If you are allowing users to delete rows from a datagrid, you may want to give them the chance to confirm the delete first.

By: John Kilgo spacer.gif Date: July 17, 2003spacer.gifdownload.gifspacer.gifDownload the code. spacer.gif <?XML:NAMESPACE PREFIX = ASP />spacer.gifPrinter Friendly Version

Allowing a user to delete a row from a database table using a Datagrid is handy, but dangerous if you just delete immediately upon pressing a button. A better way is to pop up a dialog asking the user to confirm his or her desire to delete the record. To do this requires a little javascript, as well as a change in the usual way of placing a delete button (linkbutton or pushbutton) in the datagrid. Following the VS.NET way, a ButtonColumn gets added to the datagrid. The ButtonColumn, however, has no ID property and we need one in order to associate the javascript function with the button. We can get around this by adding a template column with a button rather than adding a ButtonColumn.

We add the template column as shown below in the file, ConfirmDelDG.aspx. There are several things to take note of in the .aspx file. We'll take them in order of appearance. First, between the <head>...</head> tags is our javascript function named confirm_delete. This simply pops up a confirmation dialog asking the user if he is sure he wants to delete the record. If OK is clicked, the delete happens. If Cancel is clicked, nothing happens. The second thing to note is that our first BoundColumn is an invisible column containing the ProductID (we are using the Northwind Products table), which is the primary key we will use for the delete. Most importantly, please note that we have added a Template Column in which we have placed an asp:Button (you could use a LinkButton instead if you prefer). We have given it an ID of "btnDelete" and a CommandName of "Delete". The latter is what makes it work with the Datagrid's OnDeleteCommand.

<%@ Page Language="vb" Src="ConfirmDelDG.aspx.vb" Inherits="ConfirmDelDG" AutoEventWireup="false" %>

<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="">
<script language="javascript">
function confirm_delete()
  if (confirm("Are you sure you want to delete this item?")==true)
    return true;
    return false;
<form method="post" runat="server" ID="Form1"><br><br>
<asp:DataGrid id="dtgProducts" runat="server"
              CellPadding="6" AutoGenerateColumns="False"
              OnDeleteCommand="Delete_Row" BorderColor="#999999"
              BorderStyle="None" BorderWidth="1px"
              BackColor="White" GridLines="Vertical">
  <AlternatingItemStyle BackColor="#DCDCDC" />
  <ItemStyle ForeColor="Black" BackColor="#EEEEEE" />
  <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#000084" />
    <asp:BoundColumn Visible="False" DataField="ProductID" ReadOnly="True" />
    <asp:BoundColumn DataField="ProductName" ReadOnly="True" HeaderText="Name" />
    <asp:BoundColumn DataField="UnitPrice" HeaderText="Price" DataFormatString="{0:c}"
                     ItemStyle-HorizontalAlign="Right" />
    <asp:Button id="btnDelete" runat="server" Text="Delete" CommandName="Delete" />

And now for the codebehind file ConfirmDelDG.aspx.vb. We will take a look at it in several sections for ease of discussion and hopefully easier reading. This first section just contains the usual declarations, the Page_Load subroutine and a BindTheGrid subroutine which creates a DataSet and binds the grid. Nothing out of the ordinary here.

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.WebControls

Public Class ConfirmDelDG
  Inherits System.Web.UI.Page

  Protected WithEvents dtgProducts As System.Web.UI.WebControls.DataGrid
  Private strConnection As String = ConfigurationSettings.AppSettings("NorthwindConnection")
  Private strSql As String = "SELECT ProductID, ProductName, UnitPrice " _
                           & "FROM Products WHERE CategoryID = 1"
  Private objConn As SqlConnection

  Private Sub Page_Load(ByVal Sender As System.Object, ByVal E As System.EventArgs) Handles MyBase.Load
    If Not IsPostBack Then
    End If
  End Sub

  Private Sub BindTheGrid()
    Dim adapter As New SqlDataAdapter(strSql, objConn)
    Dim ds As New DataSet()
    adapter.Fill(ds, "Products")

    dtgProducts.DataSource = ds.Tables("Products")
  End Sub

The next section is a little out of the ordinary, but easy to understand. Since we have to connect to and disconnect from the database several times, instead of repeating that code each time we have included it in two subroutines called Connect() and Disconnect(). It keeps that code in one place and saves coding keystrokes.

  Private Sub Connect()
    If objConn Is Nothing Then
      objConn = New SqlConnection(strConnection)
    End If

    If objConn.State = ConnectionState.Closed Then
    End If
  End Sub

  Private Sub Disconnect()
  End Sub

The next subroutine, dtgProducts_ItemDataBound, is the secret to making our confirmation dialog work. We must add an OnClick event handler to each delete button on the datagrid. We can make use of ItemDataBound to do this. We dimension a variable ("btn") as type Button. We then check that ItemType is type Item or type AlternatingItem. We then use the FindControl method to find a control of type Button with an ID of "btnDelete" (the ID we gave the delete button on the aspx page). Having an ID such as "btnDelete" is why we had to use a TemplateColumn rather than a ButtonColumn which has no ID property. Once we find the button, we use Attributes.Add to call our javascript routine confirm_delete().

  Private Sub dtgProducts_ItemDataBound (ByVal sender As System.Object, _
    ByVal e As DataGridItemEventArgs) Handles dtgProducts.ItemDataBound

    Dim btn As Button
    If e.Item.ItemType = ListItemType.Item or e.Item.ItemType = ListItemType.AlternatingItem Then
      btn = CType(e.Item.Cells(0).FindControl("btnDelete"), Button)
      btn.Attributes.Add("onclick", "return confirm_delete();")
    End If

  End Sub

This last section, Delete_Row(), is where the row is actually deleted. The method presented here is out of the ordinary for me in that I usually use SQL to delete the record. The technique presented here, however, first marks the row as deleted in the Dataset, and then, in a commented out section, uses the update method to actually delete the row from the database table. Because this is being run from my hosting provider's Northwind database I cannot actually delete rows from the Products table. If you run the example program you may notice seemingly odd behaviour. If you delete a row, it will seem to be deleted (it will disappear from the grid). But if you then delete another row, it will disappear, but the first row you deleted will reappear. This is normal behavior since I am not really deleting the rows from the database, only from the dataset. If you uncomment out the lines where noted, the deletes will actually occur in the database also.

  Public Sub Delete_Row(ByVal Sender As Object, ByVal E As DataGridCommandEventArgs)

    ' Retrieve the ID of the product to be deleted
    Dim ProductID As system.Int32 = System.Convert.ToInt32(E.Item.Cells(0).Text)

    dtgProducts.EditItemIndex = -1

    ' Create and load a DataSet
    Dim adapter As New SqlDataAdapter(strSql, objConn)
    Dim ds As New DataSet()
    adapter.Fill(ds, "Products")

    ' Mark the product as Deleted in the DataSet
    Dim tbl As DataTable = ds.Tables("Products")
    tbl.PrimaryKey = New DataColumn() _
                    { _
                      tbl.Columns("ProductID") _
    Dim row As DataRow = tbl.Rows.Find(ProductID)

    ' Reconnect the DataSet and delete the row from the database
    ' Following section commented out for demonstration purposes
    'Dim cb As New SqlCommandBuilder(adapter)
    'adapter.Update(ds, "Products")
    ' Display remaining rows in the DataGrid
    dtgProducts.DataSource = ds.Tables("Products")

  End Sub

End Class

You may run the program here.
You may download the code here.

链接a href confirm记录的用法

小东西confirm记录下,小错误总结方便下次用1成功的删除删除   2以下没调成功的不知道为什么删除 3代码编辑器不能用,贴以下代码 看几个删除不行,原来中间用了中文空格http://www.w3....
  • sendling
  • sendling
  • 2008年12月03日 18:30
  • 2311

ASP.NET MVC - how to make users confirm the delete S...
  • SalmonellaVaccine
  • SalmonellaVaccine
  • 2014年07月10日 02:43
  • 436


  • lwjnumber
  • lwjnumber
  • 2011年03月17日 09:15
  • 2128

Hbase Coprocessor导引笔记

Coprocessors can be loaded globally on all tables and regions hosted by the region server, these are...
  • cmdssd1
  • cmdssd1
  • 2016年06月17日 15:56
  • 584


在asp.net中使用confirm可以分为两种: 1.没有使用ajax,confirm会引起也面刷新 2.使用了ajax,不会刷新 A.没有使用ajax,可以用StringBuilder来完成...
  • cdefg198
  • cdefg198
  • 2011年08月12日 21:29
  • 3566

MVC - Pass array from model to JS

var yourJavaScriptArray = @Html.Raw(Json.Encode(Model.YourDotNetArray));LINK - http://stackoverflow....
  • jameszhou
  • jameszhou
  • 2015年10月18日 01:22
  • 1045

( 弹出确认按钮 confirm(js)

  • wslyy99
  • wslyy99
  • 2009年02月27日 15:16
  • 1931

如何删除windows service (How to delete a windows service)

How to delete a windows service   Recently, I was trying to delete a windows service. Normally it...
  • vlily
  • vlily
  • 2015年09月14日 19:19
  • 1013

Multi-row Editing in the ASP.NET DataGrid...

Multi-row Editing in the ASP.NET DataGrid... This articles demonstrates how you can have multiple da...
  • hiyaolee
  • hiyaolee
  • 2004年10月06日 18:37
  • 878


  • lfANDhyy4113287211
  • lfANDhyy4113287211
  • 2013年01月03日 15:58
  • 2167
您举报文章:How to Confirm a Delete in an ASP.NET Datagrid...