We need you!

We're working hard on the next version of Developer Fusion. Let us know what you think we should be up to!

Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

Rated
Read 192,423 times

Contents

Related Categories

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

DMarko1

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"%>
<HTML>
    <body>
        <form runat="server" ID="Form1">
            <h3>Selecting, Confirming &amp; Deleting Multiple Checkbox Items In A DataGrid
                (i.e. HotMail &amp; Yahoo)</h3>
            <br>
            <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>
                    <asp:TemplateColumn>
                        <HeaderTemplate>
                            ID
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="StoreID" Text='<%# DataBinder.Eval (Container.DataItem, "ID") %>' runat="server"/>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <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" />
                </Columns>
            </ASP:DataGrid>
            <br>
            <asp:Button Text="Delete Items" OnClick="DeleteStore" ID="Confirm" runat="server" />
            <span id="OutputMsg" EnableViewState="false" runat="server" />
        </form>
    </body>
</HTML>

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 - dmarko1@aol.com
    /// 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" +
                "</script>";

            //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)
            {
                BindData();
            }

        }

        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
                try
                {
                    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
                BindData();
            }
        }

        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);
            MyDataGrid.DataBind();
            objConnect.Close();
            objConnect = null;
        }
    } //End Class
}//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 </>

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 desktop applications. Till now Jimmy has authored nearly two dozen .NET articles, published on Dot Net Junkies, 4 Guys From Rolla, Sitepoint, MSDN Academic Alliance, Developers.NET, The Official Microsoft ASP.NET Site, and here on Developer Fusion, covering various unique and advanced techniques on .NET.

Comments

  • Re: datagrid having multiple checkboxes with confirm d

    Posted by suhasini51 on 05 Dec 2006

    Hi,


      I required the same concept as in yahoomail.i am getting checkall and uncheckall in the grid.if all the items in the grid manually is checked then automatically the header c...

  • Re: [4632] Selecting, Confirming &amp; Deleting Multiple Checkbox Items In A DataGrid (i.e. HotMail &amp; Yahoo)

    Posted by Shafiqm on 25 Apr 2006

    I like your article regarding checkboxes. I have very interesting situation, can you please help me how I can solve this.


    My Gridview contains a template column which contains a checkboxlis...

  • Posted by ttvan01 on 03 Nov 2005

    Holly10sun,

    Can i ask what you did to get the selecting of each box to work? I also removed the Select All option, by removing the onclick/OnCheckedChanged from the HTML, but that alone didn't do...

  • multi check box in VB

    Posted by holly10sun on 03 Nov 2005

    I don't know if anyone got through this error. I was not able to fix the issue with the regiis suggestion either. I just took out the ability to click on box to select all and made the user select e...

  • javascript not a member of...

    Posted by ttvan01 on 02 Nov 2005

    I get the same javascript error. Tried running aspnet_regiis -i, but that didn't do the trick. did anyone else get this same error, if so how did you resolve it?