0

In my VB.NET form I have 50 groupboxes, each containing a combobox named volt. I used this code to add value to all the comboboxes:

For count = 1 To 50
    Dim volt = DirectCast(Me.Controls("volt" & count & ""), ComboBox)
    volt.Items.Add("what a code")
Next

but they were placed in different groupbox. When I rewrite it like this:

For count = 1 To 50
    Dim volt = DirectCast(groupbox1.Controls("volt" & count & ""), ComboBox)
    volt.Items.Add("what a code")
 Next

it works in in only groupbox1. How can I make affect the remaining groupboxes?

MJH
  • 2,301
  • 7
  • 18
  • 20
  • Welcome to Stackoverflow! To get the most out of the site it is important to ask good questions. A guide to asking questions is at: http://stackoverflow.com/help/how-to-ask – Stephen Rauch Jan 15 '17 at 03:54
  • 1
    You can loop through the form's `Controls` collection to access each `GroupBox` and then, inside the loop, access the `ComboBox` via the `Controls` collection of the `GroupBox`. – jmcilhinney Jan 15 '17 at 04:11

1 Answers1

2

Something like this might work for you (jmcilhinney suggestion actually):

 For Each ctl As Control In Me.Controls
     For Each cmb As Combobox In ctl.Controls.OfType(Of Combobox)()
        cmb.Text = "Volt"
     Next
 Next

But be careful with this - If your Groupboxes are in a container such as Panel or Split Container do a loop inside that and not In Me.Controls.

LuckyLuke82
  • 586
  • 1
  • 18
  • 58
  • it only affected the combox on the form, leaving the once in the groupbox – mekkakelvin Jan 17 '17 at 01:09
  • _**it only affected the combox on the form, leaving the once in the groupbox**_ - well obviously you didn't read or understand answer - Loop in controls collection (***In Me.controls***) will work only If your comboboxes are directly on form, **AND NOT** in container such as Groupbox, Panel etc.. You should loop Groupbox separately for that, easiest solution for you - but I think not correct one. In your case try like in this [link](http://stackoverflow.com/questions/15186828/loop-through-all-controls-on-a-form-even-those-in-groupboxes). You can convert to VB.NET using online converters. – LuckyLuke82 Jan 17 '17 at 06:00