UBel UBel - 1 year ago 55
Vb.net Question

check checkboxes status and write checkbox label in vb.net using a for next loop

I have several checkboxes in a groupbox on a vb 2008 express userform. I would like to check the checked status of each when clicking a command button and then write the checkboxes caption to be used in an email or print out. I've tried several methods and always end up with the same error "Invalid Cast Exception". I have read the help on msdn and still do not understand how to make it work. Here is the code I've been trying

Dim chk As CheckBox
Dim sb As New System.Text.StringBuilder
Dim names As String
For Each chk In gbInterior.Controls
If chk.Checked Then
End If
Next chk
names = sb.ToString(0, sb.Length - 32)

I have also tried the code below but cannot figure out how to check the status and print the checkbox caption.

Dim ctl As Control
For Each ctl In gbInterior.Controls
If TypeOf ctl Is CheckBox Then
MsgBox(ctl.Text & vbNewLine)
End If
Next ctl

Thank you for your help.

Answer Source
If TypeOf ctl Is CheckBox AndAlso CType(ctl, CheckBox).Checked Then  
   MsgBox(CType(ctl, CheckBox).Text & vbNewLine) 
End If