asp.netvb.netcontrolswebformsweb-controls

How to check all checkboxes on a page?


I am trying to check all the checkboxes on a webform (aspx) page, which is inside a master page, depending on the ID of the checkbox. The checkboxes are created dynamically, so I only know the prefix for finding it. So, I need to find these checkboxes by iterating the controls on the page somehow.

Here is the code behind where the checking should occur:

Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
    Dim oCheckbox As System.Web.UI.WebControls.CheckBox = Nothing
    Dim oControl As Control = Nothing
    For Each oControl In Me.Controls
        If oControl IsNot Nothing Then
            If TypeOf oControl Is System.Web.UI.WebControls.CheckBox Then
                oCheckbox = oControl
                If oCheckbox.Text.StartsWith("ClientCheckBox_") Then
                    oCheckbox.Checked = True
                End If
            End If
        End If
    Next
End Sub

Solution

  • Here is a non-jQuery example of how to do this client side. Let me know if you need any more help putting this example into practice.

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>Untitled Page</title>
        <script type="text/javascript" src="jquery-1.3.2-vsdoc2.js"></script>
    
    
        <script type="text/javascript">
    
            function selectDeselect(button) {
                var checked = (button.value === 'Select All');
                var checkboxes = document.getElementsByName('myCheckBoxGroup');                     
                for (var i = 0; i <  checkboxes.length; i++) {
                    checkboxes[i].checked = checked;
                }
    
                button.value = (checked) ? 'Deselect All' : 'Select All';           
            }
    
        </script>
    
        <style type="text/css">
    
        </style>
    </head>
    <body>
    
        <input type="button" value="Select All" onclick="selectDeselect(this);" />
    
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
        <input type="checkbox" name="myCheckBoxGroup" />
    
    </body>
    </html>