In this tutorial you will learn how to check / uncheck checkboxes in an ASP.Net Gridview using JavaScript in ASP.Net
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:GridView ID="gvEmployees" runat="server"> <Columns> <asp:TemplateField ShowHeader="False"> <HeaderTemplate> <asp:CheckBox ID="hdrChkBox" runat="server" onClick="checkAllRows(this);" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="rowChkBox" runat="server" onClick="checkUncheckHeaderCheckBox(this);" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="empId" HeaderText="Id" /> <asp:BoundField DataField="empName" HeaderText="Name" /> </Columns> </asp:GridView>
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. objRow.style.backgroundColor = "#99E5E5"; list[i].checked = true; } else { objRow.style.backgroundColor = "#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) { objRow.style.backgroundColor = "#99E5E5"; } else { objRow.style.backgroundColor = "#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; break; } } } objHeaderChkBox.checked = checked; }