Specified cast is not valid

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I know what that message means, but I sure can't figure out why I'm getting
it in this program. I have five GroupBoxes on Form1 each containing 3 to 5
radio buttons. The following code works fine for the first three groupboxes,
then gives me the error on the fourth. I must be missing SOMETHING, but I
sure don't see it.
*** Code****
Public Sub clearForm()
Dim rad As RadioButton
Dim grp As New GroupBox
Try
For Each grp In Me.Controls
For Each rad In grp.Controls
rad.Checked = False
Next
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
*** End Code ***
This is VB.Net 2003 Professional
 
In Catch, change
MsgBox(ex.Message)
to
MsgBox(grp.tostring & vblf & rad.tostring & vblf & ex.Message)
to see what is happening. My guess is that me.controls contains other
things besides groupboxes, but you won't know until you look.
 
AMercer,
I will try that, but I know for a fact that it DOES contain other
controls. How can i deal with that? I thi=ought it would skip anything that
was not a groupbox.
 
Ron,

You are testing all controls on your form and in that when it are
parentcontrols the childs as well. Therefore you have two possibilities.
When you are sure that a groupbox only contains radiobuttons you don't have
to do the second, however that much time it will not cost to do both and
prevents errors when you change something.

You are iterating through a collection of controls not a collection of
groupboxes. Therefore at the first moment it will throw and error if the
control is not a groupbox.

I changed it below for you (not tested of course)

You don't need that try and catch because when this goes ones right it goes
forever right. There are no external influences that can change that.
\\\
For Each grp As Control In Me.Controls
If TypeOf grp Is GroupBox Then
For Each rad As Control In grp.Controls
If TypeOf rad Is RadioButton Then
DirectCast(rad, RadioButton).Checked = False
End If
Next
End If
Next
///

I hope this helps,

Cor
 
Many thanks to AMercer, Anand and Cor Ligthert for your help on this. I now
see where I was going wrong. Many, many thanks!
 
Back
Top