Sunday, 23 March 2014

Checkbox in Gridview header to select and deselect all rows using JavaScript

I am going to explain how to add checkbox in header template of gridview to select/deselect all rows using javascript or without any postback.
  <asp:TemplateField>
     <HeaderTemplate>
         <asp:CheckBox ID="chkSelectAllOrders" runat="server" onclick="ChkAllOrders(this);" />
     </HeaderTemplate>
     <ItemTemplate>
         <asp:CheckBox ID="ChkOrders" runat="server"></asp:CheckBox>
     </ItemTemplate>
 </asp:TemplateField>

Call this function in gridview header template, checkbox onclick event.
  <script type="text/javascript">
        function ChkAllOrders(Checkbox) {
            var gvHeaderChkbox = document.getElementById("<%=gvOrders.ClientID %>");
            for (i = 1; i < gvHeaderChkbox.rows.length; i++) {
                gvHeaderChkbox.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = Checkbox.checked;
            }
        }
    </script>
The above javascript function just gets the gridview id in its variable named 'gvHeaderChkbox'. After that a for loop is executed on gridview rows on its length basis. Please note that you must check your checkboxes on basis of cell position in that particular row. If you specify your checkboxes on 'xth' column than it means your cell value will be 'x-1'.


That’s it!!…..Happy Programming...

No comments:

Post a Comment