DataGrid Common Solutions (3) - Select, confirm, delete multi-line checkbox list in DataGrid

zhaozj2021-02-16  59

Select, confirm, delete multi-line checkbox list

Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (ie HotMail & Yahoo) Introduction Although I do not have either a Hotmail or Yahoo email account, I do have friends that do, and I have often seen them check their email and noticed how it was all neatly displayed in a table. Right next to each item in their e-mail table was a simple little checkbox. At the bottom or top of this table you would have another checkbox giving them the ability to select all of the e-mail, and a button to submit back. Once this was done they would receive a nice popup alert to confirm what's about to happen, and then once this is OK 'ed, boom, all the selected items are deleted. .NET , of course, has the DataGrid, their finest and most popular control to date, and it should be pretty easy to get the same functionality, right? Well, not quite. Doing this with .NET is not that straightforward and functional as I would 'velked it to be. Sure it's quite easy to add an Edit / Update Button or link to each row and even a delete button to each, alongside a pop up alert as well! However, applying this delete feature to each and every button and deleting them one by one is a little maddening. Nor is the DataGrid set up in allowing a way of adding a main "select all" checkbox to easily select all of the boxes, and then applying any particular action. In this article, we will examine how to create a fully functional DataGrid with all the features you'd find set Up on hotmail or yahoo. as an added bonus we'll be Performing All of Our data tasks strictly utilizing microsoft '

s new Data Access Application Block or DAAB v2. To any who may feel a little behind with DAAB, have no fear, everything here can still be accomplished with pre-DAAB data objects as the only difference here is the data access part of it. Trust me there is a huge difference between the two, for one DAAB enable you to write about 75% less code that you would normally need when compared with regular ADO.NET! So, before we begin, download the DAAB dll from the above link , install it, and copy it into you application's bin folder and you're ready to go. Also, be sure and take a peek at the DAAB documentation that came with your installation for an overview and any questions you may have. Ok, let's get to it then. Our fully-featured DataGrid Selecting & deleting multiple items will definitely be set up quite differently than any other type of .NET DataGrid deleting you probably have seen. However, we'll still follow the same logical flow of deletion, And We'll Still Confirm Any Delete Actio ns about to take place after we have selected all our items. Much of the magic in making this work is really going to come from client-side JavaScript, that is ultimately responsible for wiring up our main "select all" checkbox to handle the selecting and deselecting of our checkboxes. Also, included is our server-side delete method that erases our data, and a DataGrid refresher method to rebind our DataGrid after we have completed our data deletion. Have a look at Figure 1 to get an idea of ​​what Your DataGrid Will Look Like: Figure 1 Here Is The Code To Set Up Our DataGrid:

selecting, confirming & deleeting multiple checkbox items in a DataGrid (IE Hotmail & Yahoo)

a

// ... rest of our custom template & bound columns

The code listed above is what makes our DataGrid set up behave just like the grids on Hotmail and Yahoo. Our .NET DataGrid will have the same functionality and options available for selecting however many items, or perhaps all, that you ' d like to delete, and once you do and submit, kiss them goodbye. DataGrid Setup The first step towards creating this functionality is to begin by adding a new DataGrid column (either before or after our main data, it does not matter) that 'll contain our individual checkboxes, but also include our main top "select all" checkbox (if and when we need to select and deselect all the checkboxes below it). to do this we first make sure our DataGrid's AutoGenerateColumns property is set to false , since we're going to create the necessary custom Header and Item Templates, alongside our necessary BoundColumns, within our DataGrid Columns section (that can be customized and could contain whatever you need them to). The only important thing to notice here, regarding our objective, is our first TemplateColumn that contains our checkboxes The main focal point with this whole application rests solely on this first Template Column and its two Sub Templates:.. HeaderTemplate and ItemTemplate Each contain the necessary checkboxes, both are wired to onClick events that executes select_deselectAll (our super-slick client-side JavaScript method) when either checkbox is checked, and in turn are fully responsible for giving us all the great functionality I've spoken of. incidentally, the WebDings font's lowercase letter "a"

give us our check symbol. Selecting and De-Selecting our Checkboxes Now that both checkboxes are wired to our multi-faceted JavaScript method, how is that one function going to determine the checkbox its dealing with, and the action it needs to carry out? Ah, here's how :-) Our function select_deselectAll, listed below, accepts two arguments:. the Checkbox's checked value, and its ID Once this function is called, and its two arguments have been passed in, it'll begin looping through our form . Next, it begins performing some conditional checking utilizing JavaScript's indexOf method to locate the appropriate checkbox, and is based on both the values ​​passed in, which it turn ultimately will give us one of several causes and effects: If the main "select all" checkbox is checked, it will select all of the DataGrid checkboxes If the main "select all" checkbox is unchecked, then all of the DataGrid checkboxes get unselected Finally, if after the main "select all" checkbox is selected and al l of the DataGrid's checkboxes are all checked, any one of those checkboxes gets unchecked, then the main checkbox is also unchecked. This way we do not end up having our checkbox's logic behaving inconsistently or erratically.

Function select_deselectall (chKVAL, IDVAL) {

Var fm = document.forms [0];

// loop through all elementsfor (i = 0; i

// Look for urheader template's checkboxif (idVal.indexof ('Checkall')! = -1) {

// Check if main checkbox is checked, the select or deselect dataGrid checkboxes if (chkval == true) {

Frm.erements [i] .checked = true;

} else {

frm.eements [i] .checked = false;

} // Work here with the Item Template's multiple checkboxes} else if (idVal.indexOf ( 'DeleteThis')! = -1) {// Check if any of the checkboxes are not checked, and then uncheck top select all checkboxif (frm .Elements [i] .checked == false) {

Frm.elements [1] .checked = false; // uncheck main select all checkbox

}

}

}

} Figure 2 shows you the effect of the JavaScript above interacting with the DataGrid when selecting the top main "select all" checkbox. Figure 2 Now, aside from this function allowing a quick full selection, you also have the option of manually selecting as many checkbox items as you wish. Next comes the tricky part in how to determine which ones were selected, and how to confirm this the instant you submit the form, and prior to actual deletion. Confirming Multiple Deletes in this section, we'll examine how to confirm multiple deletes when we submit our form. Below in Figure 3 you can now see the alert confirmation after selecting a couple of items, and then submitting the form by press the "Delete items" button. The alert takes place at any time you submit the form (as long as you have more than one checkbox selected). Figure 3 Note that this confirmation will alert with all checkboxes selected or a just a few as shown. Pressing the Delete Items button with none selected wil . L not prompt any alert Here now is how we determine what checkboxes are actually checked The first thing we did was set up our Delete Button at the end of our DataGrid;.. Just a regular asp server button We also wired a server-side Event to it - delete Store - That, When Confirmed, Will Delete The Records:

but how does That Pop-Up Alert confirmation APPEAR? Well, That's the cool. we get this by adding the code listed below to our Button server control as soon as the page loads, in our Page_Load method, by locating it using the FindControl method and then adding to the button attributes, like so: WebControl button = (WebControl) Page.FindControl ( " Confirm "); button.Attributes.Add (" onclick "," return confirmDelete (this.form); "); So, the second the page loads, it attached the Javascript handler to this button, and if you examine the HTML source Code, The Button Instalwords, Actually Looks Like this:

Cool Huh? Now, The Second this Button IS Pressed, IS When It Can Now Trigger The Client Side JavaScript Function Below:

Function confirmdelete (fm) {

// loop through all elementsfor (i = 0; i

// Look for ückboxes Onlyif (frm.elements [i] .name.indexof ('deletethis')! = - 1) {

// if any is checked the Confirm Alert, OtherWise Nothing Happensif (frm.elements [i] .checked) {

Return Confirm ('Are you so you want to delete your class (s)?')

}

}

}

} Ok, what happening here Well, the JS function above is, for all intents and purposes, not that different from the previous JavaScript function -? ". Select_deselectAll" Except, instead of determining if the main "select all" checkbox is checked, .. it actually checks to see whether if any of the DataGrid row checkboxes are checked If so, it'll then, and only then, alert you with a confirmation to proceed onto either to delete or cancel Deleting Data Now recall our asp: button above, and its default JavaScript onclick event handler attached on Page_Load. Aside from this we also notice it has another onClick event (this one being server based) that gets raised when the button is clicked, rather pressed, that'll allow it to fire The Server-Side deletestore Method to Delete Our Data: PUBLIC VOID DELETESTORE (Object Sender, Eventargs E) {

String Dgids = ""; BOOL BXSCHKD = FALSE;

Foreach (DataGridItem I in MyDataGrid.Items) {

Checkbox deletechkbxItem = (checkbox) I.FindControl ("deletethis");

IF (deletechkbxitem.checked) {

BXSCHKD = True; // Concatenate DataGrid Item with Comma for SQL DeleteDGIDS = ((Label) I.FindControl ("storeID")). Text.toString () ",";

}

}

// SET UP SQL DELETE STATEMENT, USING LastIndexof To Remove Tail Comma from String.String Deletesql = "Delete from Stores Where Stor_ID in (" Dgids.Substring (0, Dgids.lastIndexof (")) ") ";

IF (bxschkd == true) {// Execute SQL Query Only If Checkboxes Are Checked, OtherWise Error Occurs with Initial Null String

Try {

SQLHELPER.EXECUTENONQUERY (Objconnect, CommandType.text, deleteSQL); outputmsg.innerhtml = " store information has been deled. "; outputmsg.style ["Color "] =" green ";} catch (sqlexception err) {

Outputmsg.innerhtml = err.Message.toT7tring (); // an error ioccurred and the record could not be deleted "; outputmsg.style [" "] =" red ";

}

// Refresh DataBinddata ();

}

} Since having wired the two client / server methods together, it's our JavaScript code that actually intercepts this button's call and goes first. If you confirm OK, then will the deleting server-side method execute, otherwise it'll cancel all events after that point and prevent anything from posting back. Looking at the DeleteStore () method, you'll notice that it is actually does a few things. First, it set's up the string variable "dgIDs" that will hold all of our selected DataGrid IDs. Next, it loops through the DataGrid, and gathers all of the selected item ids that are based on the row's TemplateColumn ID, which is why I kept the ID control as a TemplateColumn and the rest BoundColumns as these types of controls do not support the ID property we need for referencing our data. After this, it will, upon verifying checked items, gather all the ids and assign them to our "dgIDs" variable, that'll be used with our SQL "deleteSQL" delete statement. The "deleteSQL Delete Statement Uses T he "WHERE IN" argument to perform the multiple deletes in one shot. Since we need to separate each id with a comma, you'll notice that in the loop I attach a comma after collected item each. This way we'll have all of our items clearly defined in our SQL. One problem however is that since we add on a comma after each collected item, the last one as well will include a tail-end comma and SQL will not like this. For example, once we Loop through the datagrid, Gather Up All of the selected items, and assign it to our delete string we could end up with something like this:

DELETE from Store WHERE STORE_ID IN (2, 4, 6, 7,) Notice The Last Comma; That A no-no. To quickly and easy remedy this need from the "dgIDs" string using LastIndexOf ( ",") effectively removing the last comma, and properly formatting the delete statement for SQL, like so: DELETE from Stores WHERE stor_id IN (2,4,6,7) Finally, DeleteStore proceeds to execute the query against the database. incidentally, for those wondering why I have a conditional with BxsChkd? Well it's because if I do not initially select any items, I'm returned an error on Page_Load due to our SqlHelper nothing initialized having . Therefore, by do so, our DeleteStore method will remain silent, and happily waiting in the wings until it does get the actual go ahead. So that's the crux of our DataGrid application, and technology behind doing multiple checkbox deletes a la Hotmail and Yahoo Style. And On That Note, Here's All The Code. Just Have S QL Server Ready, Daab Installed, Then Cut and Paste The Code Below, And Have Fun. Here's Our Main Page Code:

<% @ Page language = "c #" debug = "false" strict = "true" explicit = "true" inherits = "multideletedg.webform" src = "mdatagrid.aspx.cs"%>

Selecting, Confirming & DeleNG Multiple Checkbox Items in A DataGrid (IE Hotmail & Yahoo)

a

ID


< / form> and our multideletedg.webform code-behind file - mdatagrid.aspx.cs:

using System; using System.Data; using System.Data.SqlClient; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; // Import DAAB dll namespaceusing Microsoft.ApplicationBlocks.Data; namespace MultiDeleteDG {///

/// Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (ie HotMail & Yahoo) /// Author: Dimitrios Markatos - dmarko1@aol.com/ // Date: 8/2003 ///

Public class Webform: system.Web.ui.page // inherit page class {

Protected system.Web.ui.WebControls.DataGrid mydatagrid; protected system.web.ui.htmlcontrols.htmlGenericControl outputmsg; // span tag

Protected SqlConnection Objconnect;

Public void Page_load (Object Sender, Eventargs E) {

// Implement Client Side JavaScript Codestring Jsscript = "