VB.NET 用二维数组的方式动态加控制 例如在窗体上动态添加GroupBox,然后再在GroupBox里动态添加控件

因初学水平有限,最好可以说明一下,谢谢
2024年11月20日 04:34
有2个网友回答
网友(1):

下面这段代码完成,在窗体上用语句添加2个 GroupBox控件,且在每个GroupBox控件中添加4个 RadioButton 控件。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
'添加2个GroupBox

Dim MyGroupBox(2) As GroupBox
For i = 1 To 2
'将一个GroupBox控件加入到Form上
MyGroupBox(i) = New GroupBox
Me.Controls.Add(MyGroupBox(i))
'设置该GroupBox控件的属性
MyGroupBox(i).Height = 240
MyGroupBox(i).Width = 600
MyGroupBox(i).Top = (i - 1) * (240 + 20) + 20
MyGroupBox(i).Left = 20
'修改新加入控件的Text值
MyGroupBox(i).Text = "GroupBox" & CStr(i)
Next

'每个GroupBox中添加4个单选按钮
Dim MyRadioButton1(4) As RadioButton
Dim MyRadioButton2(4) As RadioButton

For i = 1 To 4
MyRadioButton1(i) = New RadioButton
Me.Controls.Add(MyRadioButton1(i))
MyRadioButton1(i).Parent = MyGroupBox(1)
'设置该GroupBox控件的属性
MyRadioButton1(i).Height = 20
MyRadioButton1(i).Width = 120
MyRadioButton1(i).Top = (i - 1) * (20 + 20) + 40
MyRadioButton1(i).Left = 20
'修改新加入控件的Text值
MyRadioButton1(i).Text = "RadioButton1_" & CStr(i)
Next

For i = 1 To 4
MyRadioButton2(i) = New RadioButton
Me.Controls.Add(MyRadioButton2(i))
MyRadioButton2(i).Parent = MyGroupBox(2)
'设置该GroupBox控件的属性
MyRadioButton2(i).Height = 20
MyRadioButton2(i).Width = 120
MyRadioButton2(i).Top = (i - 1) * (20 + 20) + 40
MyRadioButton2(i).Left = 20
'修改新加入控件的Text值
MyRadioButton2(i).Text = "RadioButton2_" & CStr(i)
Next
End Sub

网友(2):

这个需要父窗体 的属性设置