转至繁体中文版     | 网站首页 | 图文教程 | 资源下载 | 站长博客 | 图片素材 | 武汉seo | 武汉网站优化 | 
最新公告:     敏韬网|教学资源学习资料永久免费分享站!  [mintao  2008年9月2日]        
您现在的位置: 学习笔记 >> 图文教程 >> 站长学院 >> Web开发 >> 正文
How to Confirm a Delete in an ASP.NET Datagrid...         ★★★★

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

作者:闵涛 文章来源:闵涛的学习笔记 点击数:1323 更新时间:2009/4/23 10:45: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 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 norma

[1] [2]  下一页


[办公软件]在Excel中插入时间/日期TODAY和NOW函数  [网络安全]激活型触发式AutoRun.inf病毒和rose病毒的清除方案
[Web开发]asp.net c#其它语句之break、continue、goto实例介…  [Web开发]一大堆常用的超强的正则表达式及RegularExpressio…
[平面设计]制作动态GIF图像的好帮手─Coffee GIf Animator  [平面设计]功能超强的GIF动画制作软件─Ulead Gif Animator
[平面设计]AutoCAD常用快捷命令(外加中文说明)  [平面设计]AutoCAD常用快捷命令(字母类,外加中文说明)
[平面设计]AutoCAD快捷命令介绍  [平面设计]多种方法解决AutoCAD打印时出现错误
教程录入:mintao    责任编辑:mintao 
  • 上一篇教程:

  • 下一篇教程:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
      注:本站部分文章源于互联网,版权归原作者所有!如有侵权,请原作者与本站联系,本站将立即删除! 本站文章除特别注明外均可转载,但需注明出处! [MinTao学以致用网]
      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)

    同类栏目
    · Web开发  · 网页制作
    · 平面设计  · 网站运营
    · 网站推广  · 搜索优化
    · 建站心得  · 站长故事
    · 互联动态
    更多内容
    热门推荐 更多内容
  • 没有教程
  • 赞助链接
    更多内容
    闵涛博文 更多关于武汉SEO的内容
    500 - 内部服务器错误。

    500 - 内部服务器错误。

    您查找的资源存在问题,因而无法显示。

    | 设为首页 |加入收藏 | 联系站长 | 友情链接 | 版权申明 | 广告服务
    MinTao学以致用网

    Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved.
    闵涛 投放广告、内容合作请Q我! E_mail:admin@mintao.net(欢迎提供学习资源)

    站长:MinTao ICP备案号:鄂ICP备11006601号-18

    闵涛站盟:医药大全-武穴网A打造BCD……
    咸宁网络警察报警平台