Click here to Skip to main content
15,893,904 members
Articles / Web Development / HTML
Article

Check/uncheck CheckBox in a GridView using Javascript

Rate me:
Please Sign up or sign in to vote.
4.84/5 (45 votes)
29 Mar 2008CPOL 358.5K   5.1K   56   49
Check/uncheck CheckBox control inside a GridView using javascript without postback.

Introduction

Check/uncheck CheckBox control inside a GridView using javascript without postback. This article will give an idea on how to achieve this task.

Some sample code is provided under Using the code heading and complete code is available in the project download.

Background

(Forums are flooded with the questions about how to check/uncheck CheckBox control inside a GridView using javascript without postback.

How To’s:

In this article a GridView control is used. Inside the GridView control there are 3 fields. One template field and two are bound fields to display some sample data.

Inside the TemplateField a CheckBox control is placed in the HeaderTemplate (with ID cbSelectAll and Text Select All), ItemTemplate and AlternatingItemTemplate.

Using the code

Code that will be required to achieve this task.

Javascript that will be required to perform the Select All action is as follow:

JavaScript
<script type="text/javascript">
    function <code>SelectAll(id)</code>
    {
        //get reference of GridView control
        <code>var</code> grid = document.getElementById("<%= GridView1.ClientID %>");
        //variable to contain the cell of the grid
        <code>var</code> cell;

        if (grid.rows.length > 0)
        {
            //loop starts from 1. rows[0] points to the header.
            for (i=1; i<grid.rows.length; i++)
            {
                //get the reference of first column
                cell = grid.rows[i].cells[0];

                //loop according to the number of childNodes in the cell
                for (j=0; j<cell.childNodes.length; j++)
                {
                    //if childNode type is CheckBox
                    if (cell.childNodes[j].type =="checkbox")
                    {
                    //assign the status of the Select All checkbox to the cell checkbox within the grid
                        cell.childNodes[j].checked = document.getElementById(id).checked;
                    }
                }
            }
        }
    }
</script>

Code required to add an attribute of cbSelectAll CheckBox is as follow:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Binding GridView with the datasource

        //FillDataTable is a method that will return a DataTable
        //filled with some rows (code available in download)
        this.GridView1.DataSource = FillDataTable();
        this.GridView1.DataBind();
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //Find the checkbox control in header and add an attribute
        ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
                ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
    }
}

Before clicking the Select All CheckBox
GridCheckBox

After clicking the Select All CheckBox
GridCheckBox

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Arab Emirates United Arab Emirates
Faraz is working as a Senior Software Engineer for a company located in Sharjah, UAE. He likes developing new applications with the latest technologies. Mostly reponsible for web applications using Microsoft.Net. He has done MCPD so far. Other than work play guitars, sing and play PSP.

Comments and Discussions

 
GeneralUn checking the header checkbox [modified] Pin
bachijvs9-Sep-08 21:26
bachijvs9-Sep-08 21:26 
GeneralRe: Un checking the header checkbox Pin
farazsk119-Sep-08 22:41
farazsk119-Sep-08 22:41 
GeneralRe: Un checking the header checkbox Pin
bachijvs10-Sep-08 1:14
bachijvs10-Sep-08 1:14 
GeneralRe: Un checking the header checkbox Pin
mihhim26-May-09 3:35
mihhim26-May-09 3:35 
GeneralMasterPage - this doesnt work ... Pin
IsmailLunat5-Aug-08 3:18
IsmailLunat5-Aug-08 3:18 
GeneralRe: MasterPage - this doesnt work ... Pin
farazsk115-Aug-08 10:37
farazsk115-Aug-08 10:37 
GeneralRe: MasterPage - this doesnt work ... Pin
IsmailLunat5-Aug-08 22:34
IsmailLunat5-Aug-08 22:34 
GeneralRe: MasterPage - this doesnt work ... Pin
farazsk116-Aug-08 21:16
farazsk116-Aug-08 21:16 
Hi,

Just to test with I created a sample in which there is one MasterPage and one aspx page. I put the javascript in MasterPage and call it from the aspx page as shown in the following code and works fine.

Master Page:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    
    <script type="text/javascript">
        function SelectAll(id, gridId)
        {
            //get reference of GridView control
            var grid = document.getElementById(gridId);
            //variable to contain the cell of the grid
            var cell;
            
            if (grid.rows.length > 0)
            {
                //loop starts from 1. rows[0] points to the header.
                for (i=1; i<grid.rows.length; i++)
                {
                    //get the reference of first column
                    cell = grid.rows[i].cells[0];
                    
                    //loop according to the number of childNodes in the cell
                    for (j=0; j<cell.childNodes.length; j++)
                    {           
                        //if childNode type is CheckBox                 
                        if (cell.childNodes[j].type =="checkbox")
                        {
                        //assign the status of the Select All checkbox to the cell checkbox within the grid
                            cell.childNodes[j].checked = document.getElementById(id).checked;
                        }
                    }
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>

-----------------------------------------------------------------------------------

aspx Page:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField>
                    <AlternatingItemTemplate>
                        <asp:CheckBox ID="cbSelectAll" runat="server" />
                    </AlternatingItemTemplate>
                    <HeaderTemplate>
                        <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="cbSelectAll" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="ApplicationName" HeaderText="Application Name" />
                <asp:BoundField DataField="ServerName" HeaderText="Server Name" />
            </Columns>
        </asp:GridView>
    
    </div>
</asp:Content>

-----------------------------------------------------------------------------------------------------------------

.cs File
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Binding GridView with the datasource
            this.GridView1.DataSource = FillDataTable();
            this.GridView1.DataBind();
        }
    }

    /// <summary>
    /// Method that will add few rows in a DataTable and returns a DataTable
    /// </summary>
    /// <returns>DataTable</returns>
    protected DataTable FillDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ApplicationID");
        dt.Columns.Add("ApplicationName");
        dt.Columns.Add("ServerName");

        DataRow dr = dt.NewRow();
        dr[0] = "1";
        dr[1] = "Application 1";
        dr[2] = "Server 1";
        dt.Rows.Add(dr);

        DataRow dr1 = dt.NewRow();
        dr1[0] = "2";
        dr1[1] = "Application 2";
        dr1[2] = "Server 2";
        dt.Rows.Add(dr1);

        DataRow dr2 = dt.NewRow();
        dr2[0] = "3";
        dr2[1] = "Application 3";
        dr2[2] = "Server 3";
        dt.Rows.Add(dr2);

        DataRow dr3 = dt.NewRow();
        dr3[0] = "4";
        dr3[1] = "Application 4";
        dr3[2] = "Server 4";
        dt.Rows.Add(dr3);

        DataRow dr4 = dt.NewRow();
        dr4[0] = "5";
        dr4[1] = "Application 5";
        dr4[2] = "Server 5";
        dt.Rows.Add(dr4);

        DataRow dr5 = dt.NewRow();
        dr5[0] = "6";
        dr5[1] = "Application 6";
        dr5[2] = "Server 6";
        dt.Rows.Add(dr5);

        return dt;
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //Find the checkbox control in header and add an attribute
            ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
                ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "','" + this.GridView1.ClientID + "')");
        }
    }
}

Now try to use this code and see if you are missing something in your earlier code.

Hope this will solve your problem.

Faraz Shah Khan
MCP, MCAD.Net, MCSD.Net
Blog

GeneralRe: MasterPage - this doesnt work ... Pin
IsmailLunat31-Aug-08 4:12
IsmailLunat31-Aug-08 4:12 
GeneralRe: MasterPage - this doesnt work ... Pin
rperetz26-Sep-08 10:15
rperetz26-Sep-08 10:15 
GeneralRe: MasterPage - this doesnt work ... Pin
PragneshMPatel22-Jun-09 22:31
PragneshMPatel22-Jun-09 22:31 
GeneralRe: MasterPage - this doesnt work ... Pin
farazsk1123-Jun-09 1:11
farazsk1123-Jun-09 1:11 
GeneralImprovements to your JavaScript [modified] Pin
nickyt1-Apr-08 3:04
nickyt1-Apr-08 3:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.