分享
 
 
 

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

王朝asp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有