For Each... statement

G

Guest

group,

please help with the following codes below.

why would this not work... would it require casting/reflecting? if so, does
anyone show me the right codes?

Dim chk As System.Windows.Forms.CheckBox
If Not MsgBox("Are you sure you wish to clear?", MsgBoxStyle.YesNo +
MsgBoxStyle.Exclamation, "Clearing") = MsgBoxResult.Yes Then Exit Sub
For Each ctl In Me.Controls
If TypeName(ctl) = "GroupBox" Then
For Each chk In ctl.Controls
chk.Checked = False
Next
End If
Next


Please help.


Thanks in advance.


Ronin
 
M

Mattias Sjögren

why would this not work...

The enumerator returns all controls regardless of the type of your
iteration variable (chk As CheckBox in this case).

You have to do something like

For Each chk As Control In ctl.Controls
If TypeOf chk Is CheckBox Then CType(chk, CheckBox).Checked =False
Next



Mattias
 
A

Armin Zingler

Ronin said:
group,

please help with the following codes below.

why would this not work... would it require casting/reflecting? if
so, does anyone show me the right codes?

Dim chk As System.Windows.Forms.CheckBox
If Not MsgBox("Are you sure you wish to clear?",
MsgBoxStyle.YesNo + MsgBoxStyle.Exclamation, "Clearing") =
MsgBoxResult.Yes Then Exit Sub
For Each ctl In Me.Controls
If TypeName(ctl) = "GroupBox" Then
For Each chk In ctl.Controls
chk.Checked = False
Next
End If
Next


I tried it and it works here.

"Not work" means what? Compile error? Exception? Maybe either the groupbox
is not directly placed on the Form, or not all controls in the Groupbox are
checkboxes. If the latter is the case, use

For Each ctl2 as Control In ctl.Controls
if typeof ctl2 is Checkbox then
dim chk as checkbox=directcast(ctl2, checkbox)
chk.Checked = False
end if
Next



BTW, I would use

If typeof ctl is GroupBox

instead, because the compiler would discover a misspelled type name. But
this is not the reason for the problem.


Armin
 
P

Phill W.

why would this not work... would it require casting/reflecting? if so,
does
anyone show me the right codes?

Something like this :

Option Strict On
Imports System.Windows.Forms

.. . .

If MsgBox("Are you sure you wish to clear?" _
, MsgBoxStyle.YesNo Or MsgBoxStyle.Question _
, "Clearing") = MsgBoxResult.Yes _
Then
For Each possibleGB As Control In Me.Controls
If TypeOf( possibleGB ) Is GroupBox Then
For Each possibleCB As Control In ctl.Controls
If TypeOf( possibleCB ) Is CheckBox Then
DirectCast( possibleCB, Checkbox).Checked = False
End If
Next
End If
Next

End If

HTH,
Phill W.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top