0

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?

3
Contributors
4
Replies
29
Views
2 Years
Discussion Span
Last Post by Reverend Jim
0
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

Edited by cgeier

1

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

Edited by Reverend Jim

0

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.

0

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
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.