1

这是我在按钮单击事件中用于动态文本框控件的代码。代码运行良好。如果我单击该按钮 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"

但我不知道为动态控件执行此操作。

4

1 回答 1

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

End Class

于 2012-09-22T09:03:02.347 回答