Checking all CheckBoxes in a GridView

Scott Mitchell has written another fantastic article on the simple and clean implementation of providing the check/uncheck all functionality in the GridView control.

Link: Checking All CheckBoxes in a GridView

The only thing his implementation missing in the article is placing CheckBox in the header of the GridView, and using it to toggle rows CheckBoxes. I made a small modification to the existing code to add this feature:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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

    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)

        ClientScript.RegisterArrayDeclaration("CheckBoxIDs", String.Concat("'", cb.ClientID, "'"))
    Next

    '--modified code

    Dim checkAll As New CheckBox()
    checkAll.Text = ""
    checkAll.ID = "checkAll"
    checkAll.Attributes.Add("onclick", "ChangeAllCheckBoxStates(this.checked);")
    FileList.HeaderRow.Cells(0).Controls.Add(checkAll)

End Sub

0 Comments