Thursday, June 01, 2006

Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox

http://aspnet.4guysfromrolla.com/articles/053106-1.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim dirInfo As New DirectoryInfo(Request.PhysicalApplicationPath)

FileList.DataSource = dirInfo.GetFiles()
FileList.DataBind()
End If

'On every page visit we need to build up the CheckBoxIDs array

'Get the header CheckBox
Dim cbHeader As CheckBox = CType(FileList.HeaderRow.FindControl("HeaderLevelCheckBox"), CheckBox)

'Run the ChangeCheckBoxState client-side function whenever the
'header checkbox is checked/unchecked
cbHeader.Attributes("onclick") = "ChangeAllCheckBoxStates(this.checked);"

For Each gvr As GridViewRow In FileList.Rows
'Get a programmatic reference to the CheckBox control
Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox)

'Add the CheckBox's ID to the client-side CheckBoxIDs array
ClientScript.RegisterArrayDeclaration("CheckBoxIDs", String.Concat("'", cb.ClientID, "'"))
Next
End Sub


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);
}
}

No comments:

Blog Archive