by JBrooks
11. February 2009 11:48
Given a GridView like the one below, I want to add the ability to check the check box in the header and have that event check all of the checkboxes in each row.
I did this by adding 12 lines of JavaScript code and adding 1 attribute to my header template. Below is the markup followed by the code-behind. The parts I added to this simple page are in bold.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Test check all CheckBoxes</title>
<script type="text/javascript" language="javascript">
function changeAllCheckBoxes(sender) {
var gridViewRows = GetParentElementByTagName(sender, "TABLE").rows;
for (var i = 1; i < gridViewRows.length; ++i) {
gridViewRows[i].cells[0].childNodes[0].checked = sender.checked;
}
}
function GetParentElementByTagName(element, tagName) {
var element = element;
while (element.tagName != tagName)
element = element.parentNode;
return element;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Caption="Pick Some Technologies" BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="Include" SortExpression="Include">
<HeaderTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="changeAllCheckBoxes(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Technology" />
</Columns>
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
</form>
</body>
</html>
using System;
using System.Data;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Include", typeof(Boolean));
dt.Columns.Add("Name", typeof(String));
dt.Rows.Add(new Object[] { false, "C#" });
dt.Rows.Add(new Object[] { false, "ASP.Net" });
dt.Rows.Add(new Object[] { false, "SQL Server" });
dt.Rows.Add(new Object[] { false, "VB.Net" });
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}