I've trying to figure out how to do this, but errors didn't stop flooding me.

The following code works fine:

For i = 1 To 50
    Me.Controls("CheckBox" & i).Visible = True
Next i

But when I modify it to:

For i = 1 To 50
    Me.Controls("CheckBox" & i).Checked = False
Next i

I have even tried to mofify it to:

For i = 1 To 50
    System.Windows.Forms.CheckBox("CheckBox" & i).Checked = False
Next i

But the error still exsists. How would I fix this?

For Each ctrlItem As Control In Me.Controls
    If TypeOf ctrlItem Is System.Windows.Forms.CheckBox Then
        Dim myCheckBox = CType(ctrlItem, System.Windows.Forms.CheckBox)
        myCheckBox.Checked = True
    End If
Next

Or

Private Sub checkCheckBoxesStartingWith(ByVal startsWithText As String)
    For Each ctrlItem As Control In Me.Controls
        If TypeOf ctrlItem Is System.Windows.Forms.CheckBox Then
            If ctrlItem.Name.StartsWith(startsWithText) Then
                Dim myCheckBox = CType(ctrlItem, System.Windows.Forms.CheckBox)
                myCheckBox.Checked = True
            End If
        End If
    Next
End Sub

The reason is that

Me.Controls("CheckBox" & i)

evaluates to a generic control and while a generic control has a Visible property, it does not have a Checked property. That is why you have to cast it to the correct control type first. You could also use a more specific for loop which enumerates only CheckBox controls.

For Each cbx As CheckBox In Me.Controls.OfType(Of CheckBox)()
    cbx.Checked = False
Next

Thank you Reverend Jim. That code worked to uncheck all the present chechboxes. Just for future refrence, how would I modify that code to uncheck a specific range of checkboxes? Like from checkbox1 to checkbox20.

You could extract the numeric portion of the name like

For Each cbx As CheckBox In Me.Controls.OfType(Of CheckBox)()
    Dim num As Integer = CInt(cbx.Name.Substring(8))
    If num >= 1 And num <= 20 Then
        cbx.Checked = False
    End If
Next
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.