Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check all checkboxes in GroupBox

Status
Not open for further replies.

johnisotank

Technical User
Aug 8, 2008
258
GB
Hi,

I have a groupbox with 10 labels and 10 checkboxes.

I am trying to tick them all in one go but it keeps reporting the error:

Unable to cast object of type 'System.Windows.Forms.Label' to type 'System.Windows.Forms.CheckBox'.

I have another identical form with the same code and it works perfect so I don't understand whats wrong here..

Code:
 For Each ctrl As CheckBox In MyGroupBox.Controls
            ctrl.Checked = True
        Next

could anyone advise pls?

thanks
John
 
The problem is that you are looping through ALL the controls inside the GroupBox...and that includes what must be some Labels in the GroupBox. The Labels cannot be cast as a CheckBox.

In this case, you need to loop through all the controls as generic controls, check to see if the control is a checkbox, cast it as a checkbox and finally check it...

Code:
For Each ctrl As Control In Me.GroupBox1.Controls
    If TypeOf ctrl Is CheckBox Then
        DirectCast(ctrl, CheckBox).Checked = True
    End If
Next

=======================================
People think it must be fun to be a super genius, but they don't realize how hard it is to put up with all the idiots in the world. (Calvin from Calvin And Hobbs)

Robert L. Johnson III
CCNA, CCDA, MCSA, CNA, Net+, A+, CHDP
VB.NET Programmer
 
I noticed you have 10 labels and 10 checkboxes. Are those labels strictly for the checkboxes? If so, the checkboxes have their own TEXT property that you can use to "label" them, so you don't need the separate label controls.
 
Thanks Robert thats working now.

I do actually have a similar form with the same layout of groupbox and it ticks all the boxes with no problem, even with labels in there.

Anyway, not going to let that worry me!

Thanks again
John
 
Glad to help..... Did you see rjoubert's comment above???? That might be the difference.

=======================================
People think it must be fun to be a super genius, but they don't realize how hard it is to put up with all the idiots in the world. (Calvin from Calvin And Hobbs)

Robert L. Johnson III
CCNA, CCDA, MCSA, CNA, Net+, A+, CHDP
VB.NET Programmer
 
Hi rjoubert/Robert,

Yes, that explains it. I thought my other form had labels when in fact they just had TEXT assigned to the checkbox. This is why it wasn't erroring out - because there were no labels!

Thanks a lot for the help

John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top