Here you can use javascript
<script type="text/javascript">
function HeaderClick(CheckBox)
{
var TargetBaseControl = document.getElementById(grvLeaveDetails);
var TargetChildControl = "chkSelect";
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
Inputs[n].checked = CheckBox.checked;
var TotalChkBx = document.getElementById('totRows').value;
document.getElementById('hiddenChkCount').value = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox)
{
var TotalChkBx = document.getElementById('totRows').value;
var HeaderCheckBox = document.getElementById(HCheckBox);
if (CheckBox.checked && document.getElementById('hiddenChkCount').value < TotalChkBx)
document.getElementById('hiddenChkCount').value = parseInt(document.getElementById('hiddenChkCount').value) + 1;
else if (document.getElementById('hiddenChkCount').value > 0)
document.getElementById('hiddenChkCount').value = parseInt(document.getElementById('hiddenChkCount').value) - 1;
if (document.getElementById('hiddenChkCount').value < TotalChkBx)
{
HeaderCheckBox.checked = false;
}
else if(document.getElementById('hiddenChkCount').value == TotalChkBx)
{
HeaderCheckBox.checked = true;
}
}
</script>
Then call this function in gridview
<asp:gridview id="grvLeaveDetails" runat="server" autogeneratecolumns="false" bordercolor="Black" borderstyle="Solid" borderwidth="1px" onrowcreated="grvLeaveDetails_RowCreated" xmlns:asp="#unknown">
<columns>
<asp:templatefield>
<headertemplate>
<asp:checkbox id="chkAll" runat="server" onclick="javascript:HeaderClick(this);" />
</headertemplate>
ItemStyle Font-Size="11px" Font-Names="Verdana,Arial" Height="20px" Width="10%" HorizontalAlign="Center" />
<itemtemplate>
<asp:checkbox id="chkSelect" runat="server" />
</itemtemplate>
</asp:templatefield>
</columns>
</asp:gridview>
Then Take Two hidden Field in aspx Page.
<input type="hidden" id="hiddenChkCount" runat="server" value="0" />
<asp:hiddenfield id="totRows" runat="server" value="0" xmlns:asp="#unknown" />
Then used blow mention code in .cs page in RowCreated Event Of grid
protected void grvLeaveDetails_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox chkBxSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelect");
CheckBox chkBxHeader = (CheckBox)this.grvLeaveDetails.HeaderRow.FindControl("chkAll");
chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');", chkBxHeader.ClientID);
}
}
Then used hidden field value in .cs page where gridview is bind example is mention blow
grvLeaveDetails.DataSource = ds.Tables[0].DefaultView;
grvLeaveDetails.DataBind();
totRows.Value = grvLeaveDetails.Rows.Count.ToString();
Thanks,
Abhimanyu Rawat