<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="white"
BorderColor="black"
CellPadding=3
CellSpacing="0"
Font-Size="9pt"
AutoGenerateColumns="False"
HeaderStyle-BackColor="darkred"
HeaderStyle-ForeColor="white"
>
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="CheckAll" OnClick="javascript: return select_deselectAll (this.checked, this.id);" runat="server"/>
<font face="Webdings" color="white" size="4">a</font>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="DeleteThis" OnClick="javascript: return select_deselectAll (this.checked, this.id);" runat="server"/>
</ItemTemplate>
</asp:TemplateColumn>
// ... Rest of our Custom Template & Bound Columns
</Columns>
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:
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 will 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:
<asp:Button Text="Delete Items" OnClick="DeleteStore" ID="Confirm" runat="server" /> |
But how does that pop-up alert confirmation appear? Well, that's the cool thing. 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 afterwords, actually looks like this:
<input type="submit" name="Confirm" value="Delete Items" id="Confirm" onclick="return confirmDelete (this.form);" /> |
Cool huh? Now, the second this button is pressed, is when it can now trigger the client side JavaScript function below:
function confirmDelete (frm) {
} |
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) {
} |
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 the "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 each collected item. 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 won't 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 Stores WHERE stor_id IN (2,4,6,7,) |
Notice the last comma; that's a no-no. To quickly and easily remedy this, we must remove the last comma, and we do this by pulling the substring we 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 don't initially select any items, I'm returned an error on Page_Load due to our SqlHelper having nothing initialized. 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 SQL 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"%> <html> <form runat="server"> <h3>Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (i.e. HotMail & Yahoo)</h3>
<br> <asp:Button Text="Delete Items" OnClick="DeleteStore" ID="Confirm" runat="server" /> <span id="OutputMsg" EnableViewState="false" runat="server"/> </form> </body> |
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 namespace namespace MultiDeleteDG /// <summary>
}//End Namespace |
Conclusion
Well, that's it. Pretty awesome, and there was sure a lot to grasp as this certainly was a fairly complex article; but look at what you can do with a DataGrid now? There's nothing preventing you from adding paging to it although you'll have to delete whatever you need per page before paging to the next, or you could also store all your selected values in View State or any of of state methods, then pull them from there at the end.
At any rate, .NET clearly demonstrates that its Framework and all included is simply the best once again. Period!
Until next time. Happy .NETing