Getting controls from groupPanel

Bozzy

Active member
Joined
Aug 31, 2007
Messages
27
Programming Experience
Beginner
Hi,

I have some Radio Controls in a Group Panel and I would like to somehow loop through them and find if one of them is checked.

Here is my code to loop through these radio controls:
VB.NET:
For Each control As CheckBox In groupGraphics.Controls 
    If control.Checked Then 
        If control.Text.Equals("Other") Then 
            _Graphics = textGraphicsOther.Text 
        Else 
            _Graphics = control.Text 
        End If 
    End If 
Next

It gives the following error:
Unable to cast object of type 'System.Windows.Forms.Label' to type 'System.Windows.Forms.CheckBox'.

I am thinking that one of the reasons it could be giving this error is beacuse there is also a Label in the group as well as the radio controls.

Can anybody help me with this error?

Cheers,
Bozzy
 
Do this instead:

VB.NET:
For Each control As CheckBox In groupGraphics.Controls 
if(typeof control is RadioButton)
    If control.Checked Then 
        If control.Text.Equals("Other") Then 
            _Graphics = textGraphicsOther.Text 
        Else 
            _Graphics = control.Text 
        End If 
    End If 
Endif
next
 
VB.NET:
For Each control In groupGraphics.Controls 
If TypeOf control Is CheckBox Then
    If control.Checked Then 
        If control.Text.Equals("Other") Then 
            _Graphics = textGraphicsOther.Text 
        Else 
            _Graphics = control.Text 
        End If 
    End If 
End If
Next

That will fix your issue. Your code was castgin every control in the group box to a CheckBox, hence throwing an error when it found something that wasn't already a CheckBox control.
 
Back
Top