I have a form with a lot of checkboxes on it. I want to be able to set all the checkbox properties to "checked" in my code. Here is what I would like to do:

    For Each ctl As Control In Me.Controls
        If TypeOf ctl Is CheckBox Then
            ctl.checked = True     <===== This does not work
          End If
    Next

I may have to put the checkboxes in a container. How would I expand the code to look at the checkboxes only in GroupBox1?

I am sure this is very simple, but I have hit a dead end trying to figure it out!

Recommended Answers

All 2 Replies

You are referencing the checkboxes as generic controls and the generic control does not have a Checked property. Try referencing as Checkboxes as

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

As you pointed out this only looks at controls that are directly in the form. If the controls are in another containing control such as a GroupBox then this won't work. You'd have to rewrite as

For Each gbx As Groupbox In Me.Controls.OfType(Of GroupBox)()
    For Each cbx As CheckBox In gbx.Controls.OfType(Of CheckBox)()
        cbx.Checked = True
    Next
Next

That will handle all CheckBoxes in all GroupBoxes. You can just do a specific GroupBox by

For Each cbx As CheckBox In GroupBox1.Controls.OfType(Of CheckBox)()
    cbx.Checked = True
Next

Very nice. Thank you.

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.