21.8.10

Check gridview header checkbox if all item checkbox are checked


<script language="javascript" type="text/javascript">
<!--

function ChangeCheckBoxState(id, checkState) {
var cb = document.getElementById(id);
if (cb != null)
cb.checked = checkState;
}

function ChangeAllCheckBoxStates(checkState) {
// Toggles through all of the checkboxes defined in the CheckBoxIDs array
// and updates their value to the checkState input parameter
if (CheckBoxIDs != null) {
for (var i = 0; i < CheckBoxIDs.length; i++)
ChangeCheckBoxState(CheckBoxIDs[i], checkState);
}
}

function ChangeHeaderAsNeeded() {
// Whenever a checkbox in the GridView is toggled, we need to
// check the Header checkbox if ALL of the GridView checkboxes are
// checked, and uncheck it otherwise
if (CheckBoxIDs != null) {
// check to see if all other checkboxes are checked
for (var i = 1; i < CheckBoxIDs.length; i++) {
var cb = document.getElementById(CheckBoxIDs[i]);
if (!cb.checked) {
// Whoops, there is an unchecked checkbox, make sure
// that the header checkbox is unchecked
ChangeCheckBoxState(CheckBoxIDs[0], false);
return;
}
}

// If we reach here, ALL GridView checkboxes are checked
ChangeCheckBoxState(CheckBoxIDs[0], true);
}
}

-->
</script>


protected void grdStudents_DataBound(object sender, EventArgs e)
{
if (grdStudents.Rows.Count > 0)
{
CheckBox cbHeader = (CheckBox)grdStudents.HeaderRow.FindControl("HeaderLevelCheckBox");

cbHeader.Attributes["onclick"] = "ChangeAllCheckBoxStates(this.checked);";

List<String> ArrayValues = new List<string>();
ArrayValues.Add(String.Concat("'", cbHeader.ClientID, "'"));

foreach (GridViewRow gvr in grdStudents.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("chkSelect");
cb.Attributes["onclick"] = "ChangeHeaderAsNeeded();";
ArrayValues.Add(String.Concat("'", cb.ClientID, "'"));
}

CheckBoxIDsArray.Text = @"<script type=""text/javascript"">" + "\r\n" +
"<!--" + "\r\n" +
String.Concat("var CheckBoxIDs = new Array(", String.Join(",", ArrayValues.ToArray()), ");") + "\r\n" +
"// -->" + "\r\n" +
"</script>";
}
}

No comments: