0

我的程序在运行时创建了一个复选框数组,如下所示:

For Looper = 0 To 36
  Dim Ex1ConfigCheck As New CheckBox                    
  frmSetup.Controls.Add(Ex1ConfigCheck)                ' Add Control to from
  Ex1ConfigCheck.Top = (Looper + 45) + (Looper * 18)   ' Set Location
  Ex1ConfigCheck.Left = 210
  Ex1ConfigCheck.Text = Setup.ExCheckName(Looper)      ' Set Text property from strArray
Next

这是我不知道如何进行的地方。

我想用 Ex1configCheck().Checked 的值填充一个布尔数组(例如 MyBoolean(37))。我想填充另一个数组的原因是因为我需要能够在代码的其他部分引用复选框的值,但在创建它们之前无法访问它们。另外,我计划将数组保存到二进制文件中。

有人可以指出我正确的方向吗?

4

2 回答 2

0

If there are no other CheckBoxes in the same container as those ones then you can do this:

Dim flags = Me.Controls.OfType(Of CheckBox)().
                        Select(Function(cb) cb.Checked).
                        ToArray()

If the controls are in a different container than the form itself, replace Me with that container.

As suggested by @Jimi, you could also create a List(Of CheckBox) and assign that to a field, populating it when you create the controls. You can then use that list instead of creating one on demand:

Dim flags = myCheckBoxList.Select(Function(cb) cb.Checked).
                           ToArray()

Of course, if you know exactly how many CheckBoxes you are going to be adding, why do you need to wait until run time to create them? Why can't you create them at design time and then modify them at run time? You usually only create controls at run time if you don't know how many there will be until run time, but that seems not to be the case here.

于 2020-04-09T03:52:07.817 回答
0

Thanks all for your answers and comments. I always have a fear of being roasted when I ask what some may consider a simple question online.

I have found an alternative way of accomplishing my task. Instead of creating 8 "Arrays" of checkboxes, I have learned of a very simple control available called "CheckedListBox".

I really didn't need to create the checkboxes at runtime but was trying to find an easier way to create 8 groups of 37 checkboxes without having to manually name and set the properties of each one during design. I also wanted to be able to index them in my code to be able to update and read the value using simple loops. I could have done this by creating arrays of CheckBox but again, I would have had to manually initialize the arrays.

Once I found the CheckedListBox, I was able to accomplish what I want very quickly. I only had to set the properties of the 8 "groups" (CheckedListBox's) and fill them using the items property. The ListBox essentially created a List like Jimi suggested automatically and I can index thru each list with a loop as desired. Jimi's suggestion actually lead me to finding the CheckedListBox while I was searching for more information on using "List(of CheckBox)".

Sometimes talking to others helps me find the right questions to ask. Google was able to figure out what I wanted when I searched for "List(of CheckBox)". (:

于 2020-04-09T12:56:29.440 回答