是否可以使用
将项目添加到Form2上的列表框中If i = 1 Then
Form2.listbox1.items.add(item)
elseif i = 2 Then
Form2.listbox2.items.add(item)
End if
我希望实现像
这样的东西Form2.listbox(i).items.add(item) '<-- I know this is not the correct way.
请帮助
答案 0 :(得分:0)
如果在窗体上有很多控件(150个ListBoxes),最好在运行时动态创建它们,用项填充它们,然后将ListBox框添加到Form2上的Controls。首先,你必须加载Form2,(但它不必显示)。
在下面的代码中,首先将ListBox添加到Form2(不必是可见的,但必须实例化)。然后通过Casting设置或获取所有ListBox项值,其中使用控件的名称和类型来更改控件参数。当您知道控件的名称时,将使用强制转换“Ctype”命令,并且只有控件名称已知时才能访问和更改控件的参数。
Dim myfrm2 As New Form2 'instantiates Form 2 as an object
'myfrm2.Show() ' Use this if you want to show Form2 on the screen
'next, create 150 ListBox controls and add them to Form2's control
Dim Cnt as Integer = 0
For k = 1 To 6
For i = 1 to 25
Cnt += 1
Dim lbx As New ListBox
str = "Form2_ListBox_" & Cnt
lbx.Name = str
lbx.Left = (k-1) * 80 + 50
lbx.Top = 50 + 25 * i
lbx.Width = 50
lbx.TextAlign = System.Drawing.ContentAlignment.MiddleRight
myfrm2.Controls.Add(lbx)
Next
Next
'Assume there are 10 list items per list box
'To set ListBox values in Form 2:
Dim arraylbvalues(150,10) as Object
'fill array above with text or numbers
For i = 1 to 150
For j = 1 to 10
CType(myfrm2.Controls("Form2_ListBox_" & i ), ListBox).Items(j) = arraylbvalues(i, j)
Next j
Next i
'To get ListBox values in Form 2:
For i = 1 to 150
For j = 1 to 10
arraylbvalues(i, j) = CType(myfrm2.Controls("Form2_ListBox_" & i ), ListBox).Items(j)
Next j
Next i
另外,如果您还没有创建Form2,请将上面的第一个命令修改为:
Dim myfrm2 as New Form