VB.NET中的动态控制

时间:2012-09-22 08:49:16

标签: vb.net dynamic

这是我在按钮点击事件中动态文本框控件的代码。代码运行良好。如果我单击按钮3次,则会生成3个文本框。但我不知道将文本框值分配给变量。我不知道动态生成控件的名称。如果我想为第三个文本框添加值,该怎么做?

Dim txtBx As TextBox
Static x As Integer
Static i As Integer

txtBx = New TextBox

txtBx.Location = New Point(10, 10 + x)
txtBx.Size = New Size(100, 20)

i = i + 1
x = x + 20

Me.Controls.Add(txtBx)

如果我创建普通文本框,我可以使用,

TextBox3.Text = "Some value"

但我不知道为动态控件做这件事。

1 个答案:

答案 0 :(得分:1)

这是一个例子,将引用存储在List(Of Textbox)中:

Public Class Form1

Private tbList As New List(Of TextBox)

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim tb As TextBox
    Dim n As Integer

    n = tbList.Count + 1
    tb = New TextBox
    With tb
        .Location = New Point(10, 10 + (n * 20))
        .Name = "dynTB" & n.ToString
        .Size = New Size(100, 20)
    End With
    Me.tbList.Add(tb)
    Me.Controls.Add(tb)

End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    ' Testing:
    If Me.tbList.Count >= 3 Then Me.tbList(2).Text = "This is textbox 3"
End Sub

Private tbList As New List(Of TextBox) Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim tb As TextBox Dim n As Integer n = tbList.Count + 1 tb = New TextBox With tb .Location = New Point(10, 10 + (n * 20)) .Name = "dynTB" & n.ToString .Size = New Size(100, 20) End With Me.tbList.Add(tb) Me.Controls.Add(tb) End Sub Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click ' Testing: If Me.tbList.Count >= 3 Then Me.tbList(2).Text = "This is textbox 3" End Sub