Looping through controls

hagadorn

New member
Joined
Feb 12, 2008
Messages
2
Programming Experience
1-3
Hi im trying to loop through only the listviews in a group that i have on my form. Here is the code i am using at the moment:

VB.NET:
'disable all but the processor group to allow the form to be filled in the correct order
        For Each grp As GroupBox In Me.Controls
            If grp.Name <> "grpProcessors" Then
                grp.Enabled = False
                For Each lst As ListView In grp.Controls
                    lst.Items.Clear()
                Next
                For Each txt As TextBox In grp.Controls
                    txt.Text = ""
                Next
            End If
        Next

The problem with this is that if a certain control in the grp.controls list is not a listview then the programme crashes. The same problem is present in looping through the groupboxes on the form however if there are no non-groupbox controls then the loop works. How would i loop through the list of controls and only find the listview boxes?
 
"for each .. in controls" iterates ALL controls in the collection, and not all of them may be groupboxes etc.
VB.NET:
for each c as control in x.controls
  if typeof c is groupbox then
    directcast(c, groupbox).enabled = true

  end if
next
 
When you upgrade to VB 2008 you can do similar to what you first tried, for example by extension methods:
VB.NET:
For Each b In Me.Controls.OfType(Of Button)()

Next
and LINQ:
VB.NET:
For Each b As Button In From c In Me.Controls Where TypeOf c Is Button

Next
 
Back
Top