UBel
UBel

Reputation: 71

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
            sb.Append(chk.Text)
        End If
    Next chk
    names = sb.ToString(0, sb.Length - 32)
    MsgBox(names)

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.

Upvotes: 1

Views: 6440

Answers (3)

UnhandledExcepSean
UnhandledExcepSean

Reputation: 12804

Your problem stems from looping through all the controls on a form and trying to set each control to a control of type checkbox. A checkbox is only a single type of control and a button can't be cast into it, so that is why you are getting casting issues.

Dim ctrl As Control
Dim sb As New System.Text.StringBuilder
Dim names As String
For Each ctrl In gbInterior.Controls
    If TypeOf ctrl Is CheckBox andalso CType(ctrl, CheckBox).Checked Then
        sb.Append(CType(ctrl, CheckBox).Text)
    End If
Next ctrl 
names = sb.ToString(0, sb.Length - 32)
MsgBox(names)

Upvotes: 1

LarsTech
LarsTech

Reputation: 81610

It looks like you are looking for the Checked property on a Control, which doesn't have a property like that.

Try declaring your variable as a CheckBox and filter your list by the control type:

For Each chk As CheckBox In gbInterior.Controls.OfType(Of CheckBox)()
  If chk.Checked Then
    sb.Append(chk.Text)
  End If
Next

Upvotes: 4

NoAlias
NoAlias

Reputation: 9193

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

Upvotes: 0

Related Questions