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,200 3 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. 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. aspx file. we'll take them in order of appearance. first, between the 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 cocould 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> <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 processing 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. webcontrolsPublic class confirmdeldg Inherits system. Web. UI. Page Protected withevents dtgproducts as system. Web. UI. webcontrols. DataGrid Private strconnection as string = configurationsettings. receivettings ("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 attached ded 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 ifIf 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. itemdataboundDim 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.