(CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

In one of my previous blog post, I Described about Mutually Exclusive CheckBox inside GridView.

In this example, there is a "Select All" checkbox in header to select/deselect all the checkboxes inside GridView. MoreOver, if user select all the checkboxes manually one by one, then header checkbox should automatically be selected and vice versa.

Here is the Scenario; There is one TemplateColumn in GridView which is used to Select Row within GridView. So, There will be CheckBox inside ItemTemplate of that TemplateColumn. User would be able to select more than one CheckBox in that Column. And to Select All the CheckBoxes of that colum, There will be a "Select All" CheckBox in HeaderTemplate of that GridView. When user check "Select All" CheckBox in Header, all the checkboxes should be selected and vice versa.



Below is the GridView in my ASPX Page:

        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" CellPadding="4" ForeColor="#333333" GridLines="None">
                <Columns>
                    <asp:TemplateField HeaderText="Select">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>
                        <HeaderTemplate>
                            <asp:CheckBox ID="chkSelectAll" runat="server" Text="Select All" onclick="SelectAll(this);" />
                        </HeaderTemplate>
                    </asp:TemplateField>                    
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                </Columns>
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <EditRowStyle BackColor="#999999" />
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            </asp:GridView>
        </div>


As I said, if user select all the checkboxes manually one by one, then header checkbox should automatically be selected and vice versa; for that we have to handle GridView_RowDataBound event handler to attach the JavaScript on "OnClick" event of all CheckBoxes inside GridView.
Below is the Code Behind; where we are attaching the JavaScript on "OnClick" of CheckBox:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {                
                string strScript = "SelectDeSelectHeader(" + ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).ClientID + ");";
                ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).Attributes.Add("onclick", strScript);                
            }            
        }
        catch (Exception Ex)
        {
            //report error
        }        
    }

Finally, Below is the JavaScript (to Select/DeSelect all the CheckBoxes inside GridView) which is attached to CheckBox in HeaderTemplate:

    function SelectAll(CheckBox)
    {
        TotalChkBx = parseInt('<%= this.GridView1.Rows.Count %>');    
        var TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
        var TargetChildControl = "chkSelect";   
        var Inputs = TargetBaseControl.getElementsByTagName("input");
        for(var iCount = 0; iCount < Inputs.length; ++iCount)
        {                
            if(Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0)
                Inputs[iCount].checked = CheckBox.checked;   
        }
    }

and another JavaScript function that will select the Header "Select All" CheckBox if user select all the checkboxes manually and vice versa:

    function SelectDeSelectHeader(CheckBox)
    {        
        TotalChkBx = parseInt('<%= this.GridView1.Rows.Count %>');    
        var TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
        var TargetChildControl = "chkSelect";   
        var TargetHeaderControl = "chkSelectAll";   
        var Inputs = TargetBaseControl.getElementsByTagName("input");
        var flag = false;
        var HeaderCheckBox;
        for(var iCount = 0; iCount < Inputs.length ; ++iCount)
        {    
            if(Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetHeaderControl,0) >= 0)            
                HeaderCheckBox = Inputs[iCount];            
            if(Inputs[iCount] != CheckBox && Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0 && Inputs[iCount].id.indexOf(TargetHeaderControl,0) == -1)
            {            
                if(CheckBox.checked)
                {                    
                    if(!Inputs[iCount].checked)                    
                    {                    
                        flag = false;
                        HeaderCheckBox.checked = false;                       
                        return;
                    }
                    else
                        flag = true;                    
                }
                else if(!CheckBox.checked)                
                    HeaderCheckBox.checked = false;                                                       
            }            
        }                      
        if(flag)        
            HeaderCheckBox.checked = CheckBox.checked        
    }

Hope it will help them who want to develop some what similar or exact this functionality.

 

Comments

# (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript &laquo; KaushaL.NET

Pingback from  (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript « KaushaL.NET

# re: (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

Wednesday, August 06, 2008 5:24 AM by desideveloper

Hi.

Thanks for the article.

I am having a problem with implementing the code on my side. My page is contained in a Master Page.

The Javascript generated on the page<script type="text/javascript">

//<![CDATA[

function SelectAll(Rows,GridName,SelectAll)

{

TotalChkBx = parseInt(Rows);

var TargetBaseControl = document.getElementById(GridName);

var TargetChildControl = "chkSelect";

var Inputs = TargetBaseControl.getElementsByTagName("input");

for(var iCount = 0; iCount < Inputs.length; ++iCount)

{

if(Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0)

Inputs[iCount].checked = document.getElementById(SelectAll).checked;

}

}

//]]>

</script>

and the grid part that makes use of the script is:

<table cellspacing="0" rules="all" border="1" id="ctl00_ContentPlaceHolder1_grdMandatesList" style="width:100%;border-collapse:collapse;">

<tr class="tableViewHeader">

<th align="left" scope="col" style="width:30px;">

                                                                   <input id="ctl00_ContentPlaceHolder1_grdMandatesList_ctl01_chkSelectAll" type="checkbox" name="ctl00$ContentPlaceHolder1$grdMandatesList$ctl01$chkSelectAll" onclick="BLOCKED SCRIPTSelectAll(5,ctl00_ContentPlaceHolder1_grdMandatesList,ctl00_ContentPlaceHolder1_grdMandatesList_ctl01_chkSelectAll);" />

And the code behind is:

[code]

protected void Page_Load(object sender, EventArgs e)

{

           if (!Page.IsPostBack)

           {

               LoadMandatesList();

           }

           if (!Page.ClientScript.IsClientScriptBlockRegistered("MandateSelectAll"))

           {

               string strScript = Global.GetSelectAllScript();

               Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MandateSelectAll", strScript, true);

           } //I have also tried it by putting this in the code-behind of the master page

}

protected void LoadMandatesList()

{

           BindMandateList(0);

}

private void BindMandateList(int intNewPageIndex)

       {

           g_dtMandatesList = (GlobalVariables.g_AccessLevel == 1 || GlobalVariables.g_AccessLevel == 2) ?

               Mandate.GetMandatesList(g_AgencyID) : Mandate.GetMandatesList(g_AgencyID, g_AgentID);

           Global.BindGridView(ref grdMandatesList, g_dtMandatesList, intNewPageIndex);

       }

protected void grdMandatesList_RowDataBound(object sender, GridViewRowEventArgs e)

       {

           if (e.Row.RowType == DataControlRowType.Header)

           {

               string strGridName = grdMandatesList.ClientID, strSelectAll = ((CheckBox)e.Row.FindControl("chkSelectAll")).ClientID;

               string strJavascript = "BLOCKED SCRIPTSelectAll(" + g_dtMandatesList.Rows.Count + "," + strGridName + "," + strSelectAll + ")";

               ((CheckBox)e.Row.FindControl("chkSelectAll")).Attributes.Add("onclick", strJavascript);

           }

}

public static string GetSelectAllScript(int intRows)

       {

           StringBuilder strRefreshScript = new StringBuilder();

           strRefreshScript.Append("function SelectAll(Rows,GridName,SelectAll)\n");

           strRefreshScript.Append("{\n");

           strRefreshScript.Append("\t TotalChkBx = parseInt(Rows);\n");

           strRefreshScript.Append("\t var TargetBaseControl = document.getElementById(GridName);\n");

           strRefreshScript.Append("\t var TargetChildControl = \"chkSelect\"; \n");

           strRefreshScript.Append("\t var Inputs = TargetBaseControl.getElementsByTagName(\"input\");\n");

           strRefreshScript.Append("\t for(var iCount = 0; iCount < Inputs.length; ++iCount)\n");

           strRefreshScript.Append("\t {\n");

           strRefreshScript.Append("\t\t if(Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0)\n");

           strRefreshScript.Append("\t\t\t Inputs[iCount].checked = document.getElementById(SelectAll).checked;\n");

           strRefreshScript.Append("\t }\n");

           strRefreshScript.Append("}\n");

           return strRefreshScript.ToString();

       }

[/code]

Please help me figure out what could be wrong with my code.

Thanks a stack.

# re: (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

Wednesday, August 06, 2008 6:41 AM by desideveloper

Hi.

Thanks for the article.

I am having a problem with implementing the code on my side. My page is contained in a Master Page.

The Javascript generated on the page<script type="text/javascript">

//<![CDATA[

function SelectAll(Rows,GridName,SelectAll)

{

TotalChkBx = parseInt(Rows);

var TargetBaseControl = document.getElementById(GridName);

var TargetChildControl = "chkSelect";

var Inputs = TargetBaseControl.getElementsByTagName("input");

for(var iCount = 0; iCount < Inputs.length; ++iCount)

{

if(Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0)

Inputs[iCount].checked = document.getElementById(SelectAll).checked;

}

}

//]]>

</script>

and the grid part that makes use of the script is:

<table cellspacing="0" rules="all" border="1" id="ctl00_ContentPlaceHolder1_grdMandatesList" style="width:100%;border-collapse:collapse;">

<tr class="tableViewHeader">

<th align="left" scope="col" style="width:30px;">

                                                                   <input id="ctl00_ContentPlaceHolder1_grdMandatesList_ctl01_chkSelectAll" type="checkbox" name="ctl00$ContentPlaceHolder1$grdMandatesList$ctl01$chkSelectAll" onclick="BLOCKED SCRIPTSelectAll(5,ctl00_ContentPlaceHolder1_grdMandatesList,ctl00_ContentPlaceHolder1_grdMandatesList_ctl01_chkSelectAll);" />

And the code behind is:

[code]

protected void Page_Load(object sender, EventArgs e)

{

           if (!Page.IsPostBack)

           {

               LoadMandatesList();

           }

           if (!Page.ClientScript.IsClientScriptBlockRegistered("MandateSelectAll"))

           {

               string strScript = Global.GetSelectAllScript();

               Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MandateSelectAll", strScript, true);

           } //I have also tried it by putting this in the code-behind of the master page

}

protected void LoadMandatesList()

{

           BindMandateList(0);

}

private void BindMandateList(int intNewPageIndex)

       {

           g_dtMandatesList = (GlobalVariables.g_AccessLevel == 1 || GlobalVariables.g_AccessLevel == 2) ?

               Mandate.GetMandatesList(g_AgencyID) : Mandate.GetMandatesList(g_AgencyID, g_AgentID);

           Global.BindGridView(ref grdMandatesList, g_dtMandatesList, intNewPageIndex);

       }

protected void grdMandatesList_RowDataBound(object sender, GridViewRowEventArgs e)

       {

           if (e.Row.RowType == DataControlRowType.Header)

           {

               string strGridName = grdMandatesList.ClientID, strSelectAll = ((CheckBox)e.Row.FindControl("chkSelectAll")).ClientID;

               string strJavascript = "BLOCKED SCRIPTSelectAll(" + g_dtMandatesList.Rows.Count + "," + strGridName + "," + strSelectAll + ")";

               ((CheckBox)e.Row.FindControl("chkSelectAll")).Attributes.Add("onclick", strJavascript);

           }

}

public static string GetSelectAllScript(int intRows)

       {

           StringBuilder strRefreshScript = new StringBuilder();

           strRefreshScript.Append("function SelectAll(Rows,GridName,SelectAll)\n");

           strRefreshScript.Append("{\n");

           strRefreshScript.Append("\t TotalChkBx = parseInt(Rows);\n");

           strRefreshScript.Append("\t var TargetBaseControl = document.getElementById(GridName);\n");

           strRefreshScript.Append("\t var TargetChildControl = \"chkSelect\"; \n");

           strRefreshScript.Append("\t var Inputs = TargetBaseControl.getElementsByTagName(\"input\");\n");

           strRefreshScript.Append("\t for(var iCount = 0; iCount < Inputs.length; ++iCount)\n");

           strRefreshScript.Append("\t {\n");

           strRefreshScript.Append("\t\t if(Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl,0) >= 0)\n");

           strRefreshScript.Append("\t\t\t Inputs[iCount].checked = document.getElementById(SelectAll).checked;\n");

           strRefreshScript.Append("\t }\n");

           strRefreshScript.Append("}\n");

           return strRefreshScript.ToString();

       }

[/code]

Please help me figure out what could be wrong with my code.

Thanks a stack.

# re: (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

Monday, November 02, 2009 3:06 AM by Tats

Thanks for sharing bro.

# re: (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

Wednesday, December 16, 2009 6:19 AM by Yasmeen

Thanks for your help with this my code is working correctly.

# re: (CheckBox in HeaderTemplate to) Select All CheckBoxes inside a GridView using JavaScript

Friday, December 18, 2009 6:20 PM by Allesyslitomi

Generally I do not post on blogs, but I would love to mention that this post extremely forced me to try and do therefore! really nice post.  thanks, here's a similar subject you'll like <a href="www.myhypertensionsymptoms.com/aquired-pulmonary-hypertension.html">Aquired Pulmonary Hypertension</a>eatment</a>