VB.NET 动态控件 属性问题 5
先在窗体类中建一个控件的集合:
Dim TextBoxes As New List(Of TextBox)
在button1的Click事件中写:
For i = 1 To 5 '5是每次加入的数量
Dim newTextBox As New TextBox()
'newTextBox.Size = New Size(100,20) '
TextBoxes.Add(newTextBox) '加入我们的集合中
FlowLayoutPanel1.Controls.Add(newTextBox) '加到窗体的FlowLayoutPanel中去
Next i
然后button2的Click事件中:
For Each itemTextBox As TextBox In TextBoxes
'这里的itemTextBox.Text就代表每个TextBox里的文本
'如果你需要清空,调用TextBoxes.Clear()和FlowLayoutPanel.Controls.Clear()即可
Next
Public Class Form1
Dim tb1 As New TextBox
Dim tb2 As New TextBox
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
tb1.Location = New Point(50, 100)
tb2.Location = New Point(50, 150)
Me.Controls.Add(tb1)
Me.Controls.Add(tb2)
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim bl1 As String
Dim bl2 As String
If Me.Controls.Contains(tb1) Then
bl1 = tb1.Text
bl2 = tb2.Text
Else
bl1 = ""
bl2 = ""
MessageBox.Show("the textbox does not exist.")
End If
End Sub
End Class
如果是新建50个Textbox怎么办?这种方法太不方便了吧?