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

Fai*_*ikh -3 vb.net winforms

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

Ste*_*fan 5

为动态创建的控件命名

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
Run Code Online (Sandbox Code Playgroud)

程序中的其他位置:

    '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
Run Code Online (Sandbox Code Playgroud)

另一种方法是循环遍历me.controlls-collection并以这种方式找到控件(也许您已在这些控件或其他控件上设置了.tag =“ mycontrol” ...