Client Side
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 runat="server">
<title>Grid View Checkbox column Example</title>
<script type="text/javascript">
function SelectAll(id)
{
//get name of gridview control
var grid_name = document.getElementById("<%= GridView1.ClientID %>");
//specify checkbox column index in this cell variable
var cell;
if (grid_name.rows.length > 0)
{
//Get Check box column index and check/un check grid view check boxes
for (i = 1; i < grid_name.rows.length; i++)
{
//Get first column values
cell = grid_name.rows[i].cells[0];
//Get childNodes in the cell checked/unchecked
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="SelectAll" runat="server" Text="Select All" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="SelectAll" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="empname" HeaderText="Employee Name" />
<asp:BoundField DataField="sal" HeaderText="Salary" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Server side
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("eno");
dt.Columns.Add("empname");
dt.Columns.Add("sal");
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Ravindran";
dr[2] = "15000";
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1[0] = "2";
dr1[1] = "Ramesh";
dr1[2] = "7800";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "3";
dr2[1] = "Ganesh";
dr2[2] = "9000";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "4";
dr3[1] = "Arun ";
dr3[2] = "45000";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4[0] = "5";
dr4[1] = "Allen";
dr4[2] = "25000";
dt.Rows.Add(dr4);
DataRow dr5 = dt.NewRow();
dr5[0] = "6";
dr5[1] = "Michal";
dr5[2] = "23000";
dt.Rows.Add(dr5);
//Binding datasource to Grid View control
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Below code is used to check/uncheck grid view check boxes
if (e.Row.RowType == DataControlRowType.Header)
{
//Find the checkbox control in header and add an attribute
((CheckBox)e.Row.FindControl("SelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("SelectAll")).ClientID + "')");
}
}