Vous êtes sur la page 1sur 10

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

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 Version

Date: July 17, 2003

Download the code.

Printer Friendly

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 Imports Imports Imports System.Data System.Data.SqlClient System.Configuration 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
download the code

here.

Una Recomendacion

Que tal

La verdad mas que una solucin a tu problema es una racomendacin, ultimamente los mensajes de Alerta para confirmacion o notificacion estan un poco descontinuados, Porque no utilizas una vista, la cual al pulsar tu imagebutton se active y de una forma mas presentable y sin salir del contexto de tu pagina pregunte si quieres o no eliminar. El unico problema que tendras esque saldras de tu grid, pero eso se resuelve muy facil: case "DeleteRecord": this.ViewState["IdToDelete"]=e.CommandArgument.Tostring(); Multiview1.SetActiveView(viewDelete); break; se supone que en tu view viewDelete debes tener 2 Buttons, Accept y Cancel en el evento del button Accept se ejecutara la baja de tu registro,por ejemplo record.Id=this.ViewState["IdToDelete"]; y ya ese Id lo utilizas para identificar a tu registro. Eliminas y luego vuelve a recargar tu grid mediante una funcion que te treiga nuevamente los registros de la Bd, si tienes dudas please contactame

ASP.NET Popup Dialog - Confirm Delete - Javascript

Update 4/1/2004: Given numerous requests for a DataGrid Example, I added a post with full source code showing 1 way to pull this off using a DataGrid: ASP.NET Popup Dialog - Confirm Delete - Javascript - DataGrid Example In all good web applications, the user is asked to confirm whether he/she wants to delete something in case the delete button was pressed accidentally. Although it seems like a pain to do, it is actually really easy if you find it acceptable to use javascript's confirm statement, which will popup a dialog box with a particular question with ok and cancel buttons. You have no control of the title of the popup, but in IE it says Microsoft Internet Explorer and I believe it says [Javascript Application] or similar in Firebird.

The javascript code for it is simple: function confirm_delete() { if (confirm("Are you sure you want to delete the custom search?")==true) return true;

else return false;

Using code-behind, you can attach the javascript popup dialog to the button: _myButton.Attributes.Add("onclick", "return confirm_delete();"); If the button is inside a repeater (in this case called Searches), for example, which most of mine our, you have to attach it as follows by handling the ItemCreated event: override protected void OnInit(EventArgs e) { base.OnInit(e); this.Load += new System.EventHandler(this.Page_Load); Searches.ItemCreated += new RepeaterItemEventHandler(this.Item_Created); Searches.ItemCommand += new RepeaterCommandEventHandler(this.DeleteSearch_Click); } private void Item_Created(Object Sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { ImageButton _myButton = (ImageButton)e.Item.FindControl("btnDelete"); _myButton.Attributes.Add("onclick", "return confirm_delete();"); } } private void DeleteSearch_Click(object sender, RepeaterCommandEventArgs e) { int _id = Int32.Parse(e.CommandArgument.ToString()); // Do Your Thing... } Inside your repeater, you add the button as such: ... ImageButton id=btnDelete ImageUrl="images/icon_delete.gif" runat="server" CommandArgument=' ... When you click on the delete button, the javascript popup dialog asks if you want to delete the search. If you choose cancel, your DeleteSearch_Click event is never fired. If you choose ok, the event is fired and you can delete the item. Adds a bit of professionalism to your web applications without requiring a lot of effort.

Re: Gridview Delete Query

JN, Not sure how you are able to force a popup within the event handler but you can set the SqlDataSourceCommandEventArgs Cancel property to true: protected void SqlDataSource1_Deleting(object sender, SqlDataSourceCommandEventArgs e) { e.Cancel = true; } A better way to handle this whole thing is to add a popup directly to your delete button. (You will need to use a templated field for your button.) If the user clicks on the Cancel button, the event is cancelled at the browser. Much cleaner. Works with any of the asp.net button controls. Take a look at the OnClientClick property: <asp:LinkButton ID="LinkButtonDelete" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('Delete Record?');" Text="Delete" /> Hope this helps. -Andrew Robinson http://blog.binaryocean.com "JN" <> wrote in message news:... >I am using the sqldatasource to populate a gridview and I have a pop up >that > fires when the item_deleting event is triggered. > > Now in the popup, if the user clicks cancel, i dont want the delete query > to > continue. > > How do I accomplish this? > Thanks. > JN >

Andrew

Robinson 02012006, 07:28 PM

#3

JN
Posts: n/a

Re: Gridview Delete Query

Thanks Andrew, I will try your suggestions. "Andrew Robinson" <> wrote in message news:... > JN, > > Not sure how you are able to force a popup within the event handler but > you can set the SqlDataSourceCommandEventArgs Cancel property to true: > > protected void SqlDataSource1_Deleting(object sender, > SqlDataSourceCommandEventArgs e) >{ > e.Cancel = true; >} > > A better way to handle this whole thing is to add a popup directly to your > delete button. (You will need to use a templated field for your button.) > If the user clicks on the Cancel button, the event is cancelled at the > browser. Much cleaner. Works with any of the asp.net button controls. Take > a look at the OnClientClick property: > > <asp:LinkButton ID="LinkButtonDelete" runat="server" > CausesValidation="False" CommandName="Delete" > OnClientClick="return confirm('Delete Record?');" Text="Delete" /> > > Hope this helps. > > -> > Andrew Robinson > http://blog.binaryocean.com > > "JN" <> wrote in message > news:... >>I am using the sqldatasource to populate a gridview and I have a pop up >>that >> fires when the item_deleting event is triggered. >> >> Now in the popup, if the user clicks cancel, i dont want the delete query >> to >> continue. >>

>> How do I accomplish this? >> Thanks. >> JN >> > >

JN 02022006, 02:26 PM

#4

JN
Posts: n/a

Re: Gridview Delete Query

Onclientclick worked like a champ...thanks! "Andrew Robinson" <> wrote in message news:... > JN, > > Not sure how you are able to force a popup within the event handler but > you can set the SqlDataSourceCommandEventArgs Cancel property to true: > > protected void SqlDataSource1_Deleting(object sender, > SqlDataSourceCommandEventArgs e) >{ > e.Cancel = true; >} > > A better way to handle this whole thing is to add a popup directly to your > delete button. (You will need to use a templated field for your button.) > If the user clicks on the Cancel button, the event is cancelled at the > browser. Much cleaner. Works with any of the asp.net button controls. Take > a look at the OnClientClick property: > > <asp:LinkButton ID="LinkButtonDelete" runat="server" > CausesValidation="False" CommandName="Delete" > OnClientClick="return confirm('Delete Record?');" Text="Delete" /> > > Hope this helps. > > -> > Andrew Robinson > http://blog.binaryocean.com > > "JN" <> wrote in message > news:...

>>I am using the sqldatasource to populate a gridview and I have a pop up >>that >> fires when the item_deleting event is triggered. >> >> Now in the popup, if the user clicks cancel, i dont want the delete query >> to >> continue. >> >> How do I accomplish this? >> Thanks. >> JN

Vous aimerez peut-être aussi