如何在vb.net里面动态添加控件

如何在vb.net里面动态添加控件,第1张

Private WithEvents NewTextBox As TextBox

'通过使用WithEvents关键字声明一个对象变量为新的命令按钮

Private Sub Command1_Click()

If NewTextBox Is Nothing Then

Set NewTextBox = Controls.Add("VB.TextBox", "cmdNew", Form1)

NewTextBox.Move 200, 200

NewTextBox.Width = Form1.Width - 450

NewTextBox.Height = Form1.Height - 1400

NewTextBox.Visible = True

End If

End Sub

Private Sub Command2_Click()

If NewTextBox Is Nothing Then

Exit Sub

Else

Controls.Remove NewTextBox

Set NewTextBox = Nothing

End If

End Sub

你还要把过程与控件事件绑定

AddHandler 控件.事件名,addressof 事件过程

RemoveHandler 这个是取消绑定

没发现自动生存的事件过程后面还有一个Hander button1.Click之类的,这就是所谓事件句柄。反而跟过程名没关系,改成阿猫阿狗也可以。

例外也可以像 Private WithEvents obj as ControlClass 这么声明控件变量,估计像vb6那样会在下拉列表中列出事件系列。

哎呀,说了半天跑题了。 ff不存在嘛多半不是它的作用域范围内,应该把ff变量定义在类中,而不是类中的某个过程中。

最好把代码添多一点,把ff部分也添出来看看。

下面这段代码完成,在窗体上用语句添加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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11246238.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存