Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (i.e. HotMail & Yahoo)

Source Code & Conclusion

Here's our main page code:

<%@ Page Language="C#" Debug="False" Strict="True" Explicit="True" Inherits="MultiDeleteDG.WebForm" Src="mDatagrid.aspx.cs"%>
        <form runat="server" ID="Form1">
            <h3>Selecting, Confirming &amp; Deleting Multiple Checkbox Items In A DataGrid
                (i.e. HotMail &amp; Yahoo)</h3>
            <ASP:DataGrid id="MyDataGrid" runat="server" Width="700" BackColor="white" BorderColor="black"
                CellPadding="3" CellSpacing="0" Font-Size="9pt" AutoGenerateColumns="False" HeaderStyle-BackColor="darkred"
                            <asp:CheckBox ID="CheckAll" OnClick="javascript: return select_deselectAll (this.checked,;"
                                runat="server" />
                            <font face="Webdings" color="white" size="4">a</font>
                            <asp:CheckBox ID="DeleteThis" OnClick="javascript: return select_deselectAll (this.checked,;"
                                runat="server" />
                            <asp:Label ID="StoreID" Text='<%# DataBinder.Eval (Container.DataItem, "ID") %>' runat="server"/>
                    <asp:BoundColumn HeaderText="Store" Datafield="Store" runat="server" ID="Boundcolumn1" />
                    <asp:BoundColumn HeaderText="Address" Datafield="Address" runat="server" ID="Boundcolumn2" />
                    <asp:BoundColumn HeaderText="City" Datafield="City" runat="server" ID="Boundcolumn3" />
                    <asp:BoundColumn HeaderText="State" Datafield="State" runat="server" ID="Boundcolumn4" />
                    <asp:BoundColumn HeaderText="Zip" Datafield="Zip" runat="server" ID="Boundcolumn5" />
            <asp:Button Text="Delete Items" OnClick="DeleteStore" ID="Confirm" runat="server" />
            <span id="OutputMsg" EnableViewState="false" runat="server" />

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
using Microsoft.ApplicationBlocks.Data;
namespace MultiDeleteDG
    /// <summary>
    /// Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid (i.e. HotMail & Yahoo)
    /// Author: Dimitrios Markatos - [email protected]
    /// Date: 8/2003
    /// </summary>

    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 code
            string jsScript = "<script language=JavaScript> \n" +
                "<!--\n" +
                "function confirmDelete (frm) {\n\n" +
                " // loop through all elements\n" +
                " for (i=0; i<frm.length; i++) {\n\n" +
                " // Look for our checkboxes only\n" +
                " if (frm.elements[i].name.indexOf ('DeleteThis') !=-1) {\n" +
                " // If any are checked then confirm alert, otherwise nothing happens\n" +
                " if(frm.elements[i].checked) {\n" +
                " return confirm ('Are you sure you want to delete your selection(s)?')\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}\n\n\n" +
                "function select_deselectAll (chkVal, idVal) {\n" +
                "var frm = document.forms[0];\n" +
                "// loop through all elements\n" +
                " for (i=0; i<frm.length; i++) {\n" +
                " // // Look for our Header Template's Checkbox\n" +
                " if (idVal.indexOf ('CheckAll') != -1) {\n" +
                " // Check if main checkbox is checked, then select or deselect datagrid checkboxes \n" +
                " if(chkVal == true) {\n" +
                " frm.elements[i].checked = true;\n" +
                " } else {\n" +
                " frm.elements[i].checked = false;\n" +
                " }\n" +
                " // Work here with the Item Template's multiple checkboxes\n" +
                " } else if (idVal.indexOf('DeleteThis') != -1) {\n" +
                " // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox\n" +
                " if(frm.elements[i].checked == false) {\n" +
                " frm.elements[1].checked = false; // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}" +
                "//--> \n" +

            //Allows our .NET page to add client-side script blocks when page loads, instead of the conventional HTML JS tags.
            RegisterClientScriptBlock ("clientScript", jsScript);
            WebControl button = (WebControl) Page.FindControl ("Confirm");
            button.Attributes.Add ("onclick", "return confirmDelete (this.form);");
            objConnect = new SqlConnection ("server=(local);database=pubs;uid=sa;pwd=;");
            if (!IsPostBack)


        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 Delete
                    dgIDs += ((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
                    SqlHelper.ExecuteNonQuery (objConnect, CommandType.Text, deleteSQL);
                    OutputMsg.InnerHtml += "<font size=4><b>Store information has been deleted.</b></font>";
                    OutputMsg.Style["color"] = "green";
                catch (SqlException err)
                    OutputMsg.InnerHtml += err.Message.ToString(); //"<font size=4><b>An error occurred and the record could not be deleted</b></font>";
                    OutputMsg.Style["color"] = "red";
                //Refresh data

        public void BindData()
            String sqlQuery = "Select stor_id As Id, stor_name As Store, City, State, Zip from Stores";
            MyDataGrid.DataSource = SqlHelper.ExecuteDataset(objConnect, CommandType.Text, sqlQuery);
            objConnect = null;
    } //End Class
}//End Namespace


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 </>

You might also like...


About the author

Dimitrios Markatos

Dimitrios Markatos United States

Dimitrios, or Jimmy as his friends call him, is a .NET developer/architect who specializes in Microsoft Technologies for creating high-performance and scalable data-driven enterprise Web and des...

Interested in writing for us? Find out more.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“If Java had true garbage collection, most programs would delete themselves upon execution.” - Robert Sewell