Select/Deselect All CheckBoxes Inside the GridView

Ramesh S 0 Tallied Votes 315 Views Share

Sometimes you might need to have checkboxes for each row in a GridView control (like Inbox in Gmail). This code snippet helps to select/unselect all checkboxes in the GridView control by clicking the header checkbox. The selectUnselectCheckboxes() javascript function handles this fuctionality. This function is called in the CheckBox in the header template of the GriView. It loops through the GridView control, get the CheckBox elments and the select/deselects the them. I have implemented this functionality in DemoPage1.aspx.

//HTML part of DemoPage1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoPage1.aspx.cs" Inherits="DemoPage1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
	<title>GridView Sample By Ramesh S</title>

	<script type="text/javascript">
		function selectUnselectCheckboxes(chkBoxHeaderId, chkBoxIdInGrid, gridViewId) {
			var gridViewElem = document.getElementById(gridViewId);

			//get the no of rows<tr> generated by the gridview
			var gridRowsCount = gridViewElem.rows.length;

			//the controls in the gridview will have the following suffix in their ids 'GridView1_ctl0n'
			//the first element starts with 2 e.g. GridView1_ctl02_chkEmployee(first element)... GridView1_ctl10_chkEmployee(9th element)
			for (i = 2; i <= gridRowsCount; i++) {
				var ctlIndex = eval(i);
				if (ctlIndex < 10)
					ctlIndex = '0' + i;

				var chkBoxIdFull = gridViewElem.id + '_ctl' + ctlIndex + '_' + chkBoxIdInGrid;
				var chkBoxElem = document.getElementById(chkBoxIdFull);

				if (chkBoxElem != null) {
					//if the header checkbox is checked, then check the checkboxes in the grid
					if (document.getElementById(chkBoxHeaderId).checked)
						chkBoxElem.checked = true;
					else
						chkBoxElem.checked = false;
				}
			}
		}  
    
	</script>

</head>
<body>
	<form id="form1" runat="server">
	<div>
		<table width="100%">
			<tr>
				<td>
					<asp:GridView ID="GridView1" runat="server" Width="500px" BackColor="White" BorderColor="#3366CC"
						BorderStyle="None" BorderWidth="1px" CellPadding="4" OnRowDataBound="GridView1_RowDataBound"
						AutoGenerateColumns="False">
						<RowStyle BackColor="White" ForeColor="#003399" />
						<Columns>
							<asp:TemplateField>
								<HeaderTemplate>
									<asp:CheckBox ID="chkSelectAll" ToolTip="Select/Unselect all employees" onclick="selectUnselectCheckboxes(this.id, 'chkEmployee', 'GridView1');"
										runat="server" />
								</HeaderTemplate>
								<ItemTemplate>
									<asp:CheckBox ID="chkEmployee" runat="server" Checked='<%# Bind("Is_Eligible") %>' />
								</ItemTemplate>
								<HeaderStyle HorizontalAlign="Center" />
								<ItemStyle HorizontalAlign="Center" Width="50px" />
							</asp:TemplateField>
							<asp:BoundField DataField="EmpName" HeaderText="Name">
								<HeaderStyle HorizontalAlign="Left" />
							</asp:BoundField>
							<asp:BoundField DataField="EmpCode" HeaderText="Code">
								<HeaderStyle HorizontalAlign="Left" />
							</asp:BoundField>
							<asp:TemplateField HeaderText="Dept">
								<ItemTemplate>
									<asp:DropDownList ID="ddlDept" DataTextField="Dname" DataValueField="Deptno" DataSource="<%#GetAllDept()%>"
										runat="server">
									</asp:DropDownList>
								</ItemTemplate>
							</asp:TemplateField>
						</Columns>
						<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
						<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
						<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
						<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
					</asp:GridView>
				</td>
			</tr>
		</table>
	</div>
	</form>
</body>
</html>


//Code behind part of DemoPage1.aspx.cs

using System;
using System.Web.UI.WebControls;
using System.Data;
public partial class DemoPage1 : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind gridview with employee details
            BindGridView();
        }
    }

    //This method binds DataTable to GridView
    //I have created a DataTable with sample data here
    //You can fetch records from database, store it in a DataTable and bind it
    private void BindGridView()
    {
        DataTable dtEmp = new DataTable();

        dtEmp.Columns.Add("Is_Eligible", System.Type.GetType("System.Boolean"));
        dtEmp.Columns.Add("EmpName", System.Type.GetType("System.String"));
        dtEmp.Columns.Add("EmpCode", System.Type.GetType("System.Int16"));
        dtEmp.Columns.Add("Deptno", System.Type.GetType("System.Int16"));

        dtEmp.Rows.Add(new object[] { true, "Kannan", 1001, 10 });
        dtEmp.Rows.Add(new object[] { true, "Arun", 1001, 10 });
        dtEmp.Rows.Add(new object[] { false, "Jackson", 1001, 30 });
        dtEmp.Rows.Add(new object[] { true, "Raja", 1001, 20 });
        dtEmp.Rows.Add(new object[] { false, "John", 1001, 30 });

        GridView1.DataSource = dtEmp;
        GridView1.DataBind();
    }

    //This method returns a DataTable having department details to be 
    //bind with DropDownList for each record in the GridView
    public DataTable GetAllDept()
    {
        DataTable dtDept = new DataTable();

        dtDept.Columns.Add("Deptno", System.Type.GetType("System.Int16"));
        dtDept.Columns.Add("Dname", System.Type.GetType("System.String"));

        dtDept.Rows.Add(new object[] { 10, "Accounts" });
        dtDept.Rows.Add(new object[] { 20, "Sales" });
        dtDept.Rows.Add(new object[] { 30, "Operations" });

        return dtDept;
    }

    //This event is handled to bind DropDownList in the GridView
    //with department details
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlDeptNo = (DropDownList)e.Row.FindControl("ddlDept");
            string deptNo = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[3].ToString();
            if (ddlDeptNo != null)
            {
                ddlDeptNo.SelectedValue = deptNo;
            }

        }
    }

}