访问在运行时动态创建的文本框

时间:2012-04-18 12:54:41

标签: vb.net winforms

我在运行时动态添加文本框。我如何在程序中稍后访问它们?

1 个答案:

答案 0 :(得分:4)

首先命名动态创建的控件

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim MyTextBox As New TextBox
    MyTextBox.Name = "MyTextBox"
    Me.Controls.Add(MyTextBox)
end sub

该计划的其他地方:

    'set text
    Me.Controls("MyTextBox").Text = "Hi there"
    'fetch text
    Dim thetext = Me.Controls("MyTextBox").Text

    'fetch textbox
    Dim tb As TextBox = CType(Me.Controls("MyTextBox"), TextBox)
    tb.Text = ""
    tb.BackColor = Color.Red

另一种方法是遍历me.controlls-collection并找到那种方式的控件(也许你已经在那些或其他东西上设置了.tag =“mycontrol”......