How to confirm a delete in an ASP.NET DATAGRID ...

xiaoxiao2021-03-06  70

IF you are allowing users to delete rows from a datagrid, you may want to give the the life 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 , 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 Se .aspx File. We'll Take THEM IN ORDER OF APPEARANCE. First, Between the ... 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"%> 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 () {ix ("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 "forcolor =" white "backcolor =" # 000084 "/> <columns> <ask: boundcolumn visible =" false "datafield =" productID "readonly =" true "/> <</p> <p>asp: BoundColumn DataField = "ProductName" ReadOnly = "True" HeaderText = "Name" /> <asp: BoundColumn DataField = "UnitPrice" HeaderText = "Price" DataFormatString = "{0: c}" ItemStyle-HorizontalAlign = "Right" /> <Itemplate> <ask: button id = "btndelete" runat = "server" text = "delete" CommandName = "delete" /> </ itemtemplate> </ asp: templateColumn> </ columns> </ ask: 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.</p> <p>Imports System.DataImports System.Data.SqlClientImports System.ConfigurationImports System.Web.UI.WebControlsPublic 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 Subthe Next Section is a little out of the order, 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.</p> <p>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</p> <p>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) .fin DControl ("btndelete"), button btn.attributes.add ("onclick", "Return Confirm_delete ();") end if End Sub</p> <p>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 can not 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.</p> <p>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' ---------------------------------- ------------------------- '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 SubEnd ClassYou may run the program here.You may download The code here.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-110030.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="110030" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.048</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'Nw_2BYEPuxzr7E6Ku95G244J4MrFTabgvyFDzQoZTMD2KYEjV7jeBKasWVM5Ju4EKTuOiHhPmQ6_2BqqU2I646qwYA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>