I am working on a Windows program and it has about 50 or so checkboxes on one page. I have an additional checkbox to select all / deselect all but I just am not sure how to loop through all the given checkboxes to set their values to true or false.
Brian. That worked really well. However, it is affecting all checkboxes in my program. I have these key checkboxes in a TabPanel. How would I segregate these from all others. This is how I have my code setup now:
If CheckBox137.Value = False Then
For j As Integer = 0 To Self.ControlCount - 1
If Self.Control(j) IsA CheckBox Then
CheckBox(Self.Control(j)).Value = False
CheckBox137.Caption = "Select All"
End If
Next
end if
if CheckBox137.Value = True Then
For i As Integer = 0 To Self.ControlCount - 1
If Self.Control(i) IsA CheckBox Then
CheckBox(Self.Control(i)).Value = True
CheckBox137.Caption = "Deselect All"
End If
Next
End if
By giving all the checkBoxes that belong together the same name (e.g. Tab1CheckBoxes, Tab2CheckBoxes, etc), which turns them into a control array (so they have the same name but different indexes).
Then just iterate over the respective control array and turn all of them on or off.
for each cb as CheckBox in Tab1CheckBoxes
cb.value = true
next
You should avoid having two loops so similar. That’s bad practice (for example, if you need to change something later, you must make the change twice).
Also, you’re setting the Checkbox137’s caption every time you’re encountering a checkbox; just do that once, after the loop.
This code would do the same as above:
For j As Integer = 0 To Self.ControlCount - 1
If Self.Control(j) IsA CheckBox Then
CheckBox(Self.Control(j)).Value = CheckBox137.Value
End If
Next
if CheckBox137.Value=false then
CheckBox137.Caption = "Select All"
Else
CheckBox137.Caption = "Deselect All"
end if
As would this one, more compact:
For j As Integer = 0 To Self.ControlCount - 1
var Ctrl As Control=Self.Control(j) //Used twice, so keep in a variable
If Ctrl IsA CheckBox Then CheckBox(Ctrl).Value = CheckBox137.Value
Next
CheckBox137.Caption=if(CheckBox137.Value,"Deselect All","Select All")