Check and uncheck all checkboxes in ASP.Net Gridview

Mohammed Imtiyaz Jun 1, 2014

In this tutorial you will learn how to check / uncheck checkboxes in an ASP.Net Gridview using JavaScript in ASP.Net


Check and uncheck all checkboxes in ASP.Net Gridview

Key Points

If you check the header checkbox then all the checkboxes in Gridview row will be selected.

If any of the checkbox in Gridview row is unchecked, then the header checkbox will automatically get unchecked i.e, the header checkbox will be checked if an only if all the checkboxes in ridview rows are selected.

ASP.Net Gridview Control

<asp:GridView ID="gvEmployees" runat="server">
	<asp:TemplateField ShowHeader="False">

			<asp:CheckBox ID="hdrChkBox" runat="server" onClick="checkAllRows(this);" />

			<asp:CheckBox ID="rowChkBox" runat="server" onClick="checkUncheckHeaderCheckBox(this);" />

	<asp:BoundField DataField="empId" HeaderText="Id" />
	<asp:BoundField DataField="empName" HeaderText="Name" />

JavaScript Functions

We are using here two JavaScript functions. One for checking all checkboxes in Gridview and another for changing the header checkbox. The script is mentioned below.

JavaScript Function 1

// Check / Uncheck all checkboxes when the header checkbox is checked. //

function checkAllRows(obj) {

    var objGridview = obj.parentNode.parentNode.parentNode;
    var list = objGridview.getElementsByTagName("input");

    for (var i = 0; i < list.length; i++) {
        var objRow = list[i].parentNode.parentNode;
        if (list[i].type == "checkbox" && obj != list[i]) {
            if (obj.checked) {

                //If the header checkbox is checked then check all 
                //checkboxes and highlight all rows.

       = "#99E5E5";
                list[i].checked = true;
            } else {
       = "#FFFFFF";
                list[i].checked = false;

JavaScript Function 2

// Check, Uncheck header checkbox when checkboxes from Gridview rows are checked or unchecked. //

function checkUncheckHeaderCheckBox(obj) {
    var objRow = obj.parentNode.parentNode;

    if (obj.checked) { = "#99E5E5";
    } else { = "#FFFFFF";
    var objGridView = objRow.parentNode;

    //Get all input elements in Gridview
    var list = objGridView.getElementsByTagName("input");
    for (var i = 0; i < list.length; i++) {
        var objHeaderChkBox = list[0];

        //Based on all or none checkboxes are checked check/uncheck Header Checkbox
        var checked = true;

        if (list[i].type == "checkbox" && list[i] != objHeaderChkBox) {
            if (!list[i].checked) {
                checked = false;
    objHeaderChkBox.checked = checked;