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

类别:.NET开发 点击:0 评论:0 推荐:

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 Date: July 17, 2003 Download the code. Printer 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" %>

<html>
<head>
<title>ConfirmDelDG</title>
<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="http://schemas.microsoft.com/intellisense/ie5">
<script language="javascript">
function confirm_delete()
{
  if (confirm("Are you sure you want to delete this item?")==true)
    return true;
  else
    return false;
}
</script>
</head>
<body>
<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" />
  <Columns>
    <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:TemplateColumn>
    <ItemTemplate>
    <asp:Button id="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
    </ItemTemplate>
    </asp:TemplateColumn>
  </Columns>
</asp:DataGrid>
</form>
</body>
</html>

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
      BindTheGrid()
    End If
  End Sub

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

    dtgProducts.DataSource = ds.Tables("Products")
    dtgProducts.DataBind()
  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
      objConn.Open()
    End If
  End Sub

  Private Sub Disconnect()
    objConn.Dispose()
  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
    Connect()
    Dim adapter As New SqlDataAdapter(strSql, objConn)
    Dim ds As New DataSet()
    adapter.Fill(ds, "Products")
    Disconnect()

    ' 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)
    row.Delete()

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

  End Sub

End Class

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

本文地址:http://com.8s8s.com/it/it43718.htm