简体   繁体   中英

Dynamic control in VB.NET

This is my code for dynamic textbox controls in button click event. The code is working well. If i click the button 3 times, it is generated 3 text boxes. But I have no idea to assign text box values to a variable. I dont know the names of dynamic generated controls. if i want to add value to 3rd text box, how to do it?

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)

if i create normal textbox i can do it with,

TextBox3.Text = "Some value"

But I dont know to do this for dynamic controls.

Here's an example, storing the references in a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM