October 21, 2014 by Nitesh

How To Implement Select All/Unselect All CheckBoxes in GridView Rows


In my last posts, I explained How To Add CheckBox to GridView and How To Get Selected Multiple Rows From GridView. In this post, I will explain how can  you select/unselect all rows of a GridView by selecting a CheckBox in client side.

We will start with using the same GridView, we are using in our previous examples. The only difference I will make here is add a CheckBox in the header of the Checkbox column using the HeaderTemplate clicking on which will toggle the state of checkboxes in each row of the GridView. To toggle the state of check boxes, we will use a little bit of jQuery. Below is the code for the same.

Code for ASPX Page:

<asp:gridview ID="grdData" runat="server" AutoGenerateColumns="False" CellPadding="4" CssClass="grdData"
            ForeColor="#333333" GridLines="None" Width="200">
            <alternatingrowstyle BackColor="White" ForeColor="#284775"></alternatingrowstyle>
                <asp:templatefield HeaderText="Select">
                        <input type="checkbox" id="chkAll" onclick="javascript: toggleCheckboxes()" />
                        <asp:checkbox ID="cbSelect" CssClass="gridCB" runat="server"></asp:checkbox>
                <asp:boundfield DataField="ID" HeaderText="ID"></asp:boundfield>
                <asp:boundfield DataField="Name" HeaderText="Name"></asp:boundfield>
            <editrowstyle BackColor="#999999"></editrowstyle>
            <footerstyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></footerstyle>
            <headerstyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></headerstyle>
            <pagerstyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></pagerstyle>
            <rowstyle BackColor="#F7F6F3" ForeColor="#333333"></rowstyle>
            <selectedrowstyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></selectedrowstyle>
            <sortedascendingcellstyle BackColor="#E9E7E2"></sortedascendingcellstyle>
            <sortedascendingheaderstyle BackColor="#506C8C"></sortedascendingheaderstyle>
            <sorteddescendingcellstyle BackColor="#FFFDF8"></sorteddescendingcellstyle>
            <sorteddescendingheaderstyle BackColor="#6F8DAE"></sorteddescendingheaderstyle>

Javascript/jQuery Code: To be used in header/footer of the page where the grid is loaded.

    <script type="text/javascript">
        function toggleCheckboxes() {
            if ($("#chkAll").prop('checked'))
                $(".gridCB input[type='checkbox']").prop('checked', true);
                $(".gridCB input[type='checkbox']").prop('checked', false);

You’re done.

Hope you like this! Keep learning and sharing! Cheers!


Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup