Hi Vincenzo67,
Refer below sample code.
Call the HeaderClick and ChildClick on each GridView Header and DataRow CheckBox respectively.
HTML
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkHeader" onclick="HeaderClick(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkRow" onclick="ChildClick(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<hr />
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkHeader" onclick="HeaderClick(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkRow" onclick="ChildClick(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<script type="text/javascript">
function HeaderClick(headerCheckBox) {
//Get the reference of GridView.
var GridView = headerCheckBox.parentNode.parentNode.parentNode;
//Loop through all GridView Rows except first row.
for (var i = 1; i < GridView.rows.length; i++) {
//Reference the CheckBox.
var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
checkBox.checked = headerCheckBox.checked;
}
}
function ChildClick(chk) {
//Get the reference of GridView.
var GridView = chk.parentNode.parentNode.parentNode;
//Reference the Header CheckBox.
var headerCheckBox = GridView.rows[0].cells[0].getElementsByTagName("input")[0];
var checked = true;
//Loop through all GridView Rows.
for (var i = 1; i < GridView.rows.length; i++) {
//Reference the CheckBox.
var checkBox = GridView.rows[i].cells[0].getElementsByTagName("input")[0];
if (!checkBox.checked) {
checked = false;
break;
}
}
headerCheckBox.checked = checked;
}
</script>
Namespaces
using System.Data;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
dt.Rows.Clear();
dt.Rows.Add(1, "Nancy Davolio", "USA");
dt.Rows.Add(2, "Andrew Fuller", "USA");
dt.Rows.Add(3, "Janet Leverling", "USA");
dt.Rows.Add(4, "Margaret Margaret", "USA");
gvEmployees.DataSource = dt;
gvEmployees.DataBind();
}
}
Screenshot