Monday, June 29, 2009

How to Maintain Checkbox state in a Gridview for an Header

<script type="text/javascript">
function ChangeCheckBoxState(id, checkState) {
var cb = document.getElementById(id);
if (cb != null)
cb.checked = checkState;
}

function ChangeAllCheckBoxStates(checkState) {
if (EmplloyeeCheckBoxIDs != null) {
for (var i = 0; i < EmplloyeeCheckBoxIDs.length; i++)
ChangeCheckBoxState(EmplloyeeCheckBoxIDs[i], checkState);
ChangeCheckBoxState(EmplloyeeCheckBoxIDs[0], checkState);
}
}

function ChangeHeaderAsNeeded() {
if (EmplloyeeCheckBoxIDs != null) {
var txt = document.getElementById("<%= gvcountvalEmplyeeMaster.ClientID %>");
for (var i = 1; i < txt.value; i++) {
var cb = document.getElementById(EmplloyeeCheckBoxIDs[i]);
if (!cb.checked) {
ChangeCheckBoxState(EmplloyeeCheckBoxIDs[0], false);
return;
}
}
ChangeCheckBoxState(EmplloyeeCheckBoxIDs[0], true);
}
}
</script>






IN ROWDATABOUND
---------------

if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox cbHeader = (CheckBox)e.Row.FindControl("chkEmployeeHeader");
cbHeader.Attributes.Add("onclick", "ChangeAllCheckBoxStates(this.checked);");
EmplloyeeCheckBoxIDsArray.Add(string.Concat("'", cbHeader.ClientID, "'"));
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)e.Row.FindControl("chkEmployee");
cb.Attributes.Add("onclick", "ChangeHeaderAsNeeded();");
EmplloyeeCheckBoxIDsArray.Add(string.Concat("'", cb.ClientID, "'"));
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
gvcountvalEmplyeeMaster.Value = EmplloyeeCheckBoxIDsArray.Count.ToString();
EmployeeCheckBoxIDArrayScript.Text = string.Format("", System.Environment.NewLine, string.Join(",", EmplloyeeCheckBoxIDsArray.ToArray()));
}
}

Declarattion at Page Level inorder to Maintain the Count at Footer

List EmplloyeeCheckBoxIDsArray = new List();

No comments: