loop through only ComboBoxes

Hello Everyone

I feel like I should know the answer to this, but my brain is just frozen.  I want to loop through only combo boxes on a form, as they will be filled with DB table values.  This form also has multiple other controls.  I've tried something like:

dim MyControl as combobox

For each mycontrol in me.controls etc...

Problem is this fails when it hits something other than a ComboBox.  Also tried:

Dim MyControl as control.  Problem with that is .items.add () is not a member of control.  Maybe it's late and I should leave playing with this stuff to the weekend, but I'm going crazy.

I'm sure someone out there has a quick solution, so thank you in advance!!



Answer this question

loop through only ComboBoxes

  • sreeni2219

    hi,

    sorry i'm beginner but i was trying to do that b4 i guess the code that have been posted by Chris was very hellpfull but i guess you have to add something to be able to deal with this control

     For Each ctl As Control In Me.Controls

    If TypeOf ctl Is ComboBox Then
                   

    dim name as string = ctl.name

    if name = "the name that u search for then

    dim mycbobox as combobox

    mycbobox = ctype(ctl, combobox)

    mycbobox.items.add("what you want")


    End If
     Next

    again i'm only guessing because i had to do that in the webforms

    best regards



  • Nathan Baulch

    That's because the enumerator used when running the ForEach loop for your controls will try to cast each controls in the Me.Controls collecion to ComboBox, which will throw an exception when it a control is not castable to ComboBox.

    The solution for this is, just run a single type within your ForEach loop and perform Type Checking inside the loop:



            For Each ctl As Control In Me.Controls
                If TypeOf ctl Is ComboBox Then
                    MessageBox.Show("Found a ComboBox : " + ctl.Name)
                End If
            Next

     


    Regards,

    -chris

  • loop through only ComboBoxes