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






4.80/5 (2 votes)
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 you can 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 checkbox
es 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>
<columns>
<asp:templatefield HeaderText="Select">
<headertemplate>
<input type="checkbox"
id="chkAll" onclick="javascript: toggleCheckboxes()" />
</headertemplate>
<itemtemplate>
<asp:checkbox ID="cbSelect"
CssClass="gridCB" runat="server"></asp:checkbox>
</itemtemplate>
</asp:templatefield>
<asp:boundfield DataField="ID" HeaderText="ID"></asp:boundfield>
<asp:boundfield DataField="Name" HeaderText="Name"></asp:boundfield>
</columns>
<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>
</asp:gridview>
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);
else
$(".gridCB input[type='checkbox']").prop('checked', false);
}
</script>
You’re done!
Hope you like this! Keep learning and sharing! Cheers!