Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop Through Controls and Find Combobox

Status
Not open for further replies.

jasonp45

Programmer
Aug 23, 2001
212
US
On a Windows form (VB.NET app on XP), I have three combo boxes. I want to create a sub called "CheckComboNull" so that when a command-button is pressed, the sub checks to ensure that an item has been selected from each combo box on the form.

In VB6 I would just loop through the controls, look for type=combobox, and check to see if it had a value selected. How do I do this in .NET? I've looked on the web but everything I've found seems to say you can't loop through the same way, and looks unnecessarily complex.

Thanks!
 
Each container, including the form, has a ControlsCollection for conrols that are directly contained. Assuming your ComboBoxes are contained directly by the form then use
Dim cmb As ComboBox
For Each cmb In Me.Controls
..........
Next

Compare Code
 
Thanks! Doesn't seem to work though. When I run that code I get an "Specified cast is not valid" error on the For...Each line.
 
Code:
    Dim cmb As New ComboBox()
    Dim ctl As Control
    For Each ctl In Me.Controls
      If ctl.GetType Is cmb.GetType Then
        cmb = CType(ctl, ComboBox)
        'do combo box stuff here on cmb
      End If
    Next

Controls returns control objects, so you can cast from them to combo boxes. or what ever other control type you need to look at.

-Rick

----------------------
 
Rick
You can also use, which just gets rid of a few Gettype(s)
Code:
IF TYPEOF(ctl) is cmb
   cmb = CType(ctl, ComboBox)
   'do combo box stuff here on cmb
End If

Sweep
...if it works dont mess with it
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top