Introduction
- We will learn how to select all the checkboxes at one time inside the Gridview using JavaScript.
- Follow the below steps to achieve our requirement.
Step 1
Add the below code to our .aspx page.
- <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false" AllowPaging="true"
- PageSize="10″ OnPageIndexChanging="gvData_PageIndexChanging" AlternatingRowStyle-BackColor="#FFDAB9″
- HeaderStyle-BackColor="#FF8C00″ Width="800px" OnRowDataBound="gvData_RowDataBound">
- <Columns>
- <asp:BoundField DataField="id" HeaderText="id" />
- <asp:BoundField DataField="message" HeaderText="Message" />
- <asp:TemplateField>
- <HeaderTemplate>
- <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
- </HeaderTemplate>
- <ItemTemplate>
- <asp:CheckBox ID="cbSelectAll" runat="server" Checked=’<%# Convert.ToBoolean(Eval(“isapproved")) %>’
- Text=’<%# Eval(“isapproved").ToString().Equals(“True") ? " Approved " : " Not Approved " %>’ />
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
- <asp:Button ID="btnSave" runat="server" Text="save" OnClick="btnSave_Click" />
Step 2
Add the below code to our .cs page.
- protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- if (e.Row.RowType == DataControlRowType.Header)
- {
- ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick",
- "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
- }
- }
-
- protected void gvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
- {
- gvData.PageIndex = e.NewPageIndex;
- FillData();
- }
Step 3
Inside the script write the below code.
- <script type="text/javascript">
- function SelectAll(id)
- {
- var grid = document.getElementById(“<%= gvData.ClientID %>");
- var cell;
- if (grid.rows.length > 0)
- {
- for (i = 1; i < grid.rows.length – 1; i++)
- {
- cell = grid.rows[i].cells[3];
- for (j = 0; j < cell.childNodes.length; j++)
- {
- if (cell.childNodes[j].type == “checkbox")
- {
- cell.childNodes[j].checked = document.getElementById(id).checked;
- }
- }
- }
- }
- }
- </script>
Step 4
Click the save button and write the below code.
- protected void btnSave_Click(object sender, EventArgs e)
- {
- try
- {
- foreach (GridViewRow row in gvData.Rows)
- {
- if (row.RowType == DataControlRowType.DataRow)
- {
- CheckBox c = (CheckBox)row.FindControl(“cbSelectAll“);
- bool cbValue = c.Checked;
- string cid = row.Cells[0].Text;
-
- FillData();
- }
- }
- }
- catch { }
- }
-
- protected void FillData()
- {
-
- }
In the above code, to catch the checked values of each checkbox, the below code is used.
- foreach (GridViewRow row in gvData.Rows)
- {
- if (row.RowType == DataControlRowType.DataRow)
- {
- CheckBox c = (CheckBox)row.FindControl(“cbSelectAll“);
- bool cbValue = c.Checked;
- }
- }