Public Class frmControl_Dynamic
'Liste für Referenzen auf Textboxen
Dim tbo_list As New List(Of TextBox)
Const tbo_Max As Integer = 10
Dim WithEvents btnCreateTBO As New Button With
{.Parent = Me, .Top = 10, .Left = 10, .Width = 200, .Text = "Add" & _
"Textbox"}
Dim WithEvents btnDeleteTBO As New Button With
{.Parent = Me, .Top = 50, .Left = 10, .Width = 200, .Text = "Delete" & _
"Textbox"}
Private Sub btnCreateTBO_Click(sender As Object, e As EventArgs) Handles _
btnCreateTBO.Click
If tbo_list.Count >= tbo_Max Then
MsgBox("Zu viele Textboxen")
Exit Sub
End If
'Control erstellen
Dim tbo As New TextBox With
{.Parent = Me, .Top = getTextBox_Top(tbo_list.Count), .Left = 10, _
.Width = 300,
.Name = getTextbox_Name(), .[ReadOnly] = True}
'Handler einrichten
AddHandler tbo.KeyDown, AddressOf tbo_keydown
'Control an Liste anhängen und Index notieren (Demo)
tbo_list.Add(tbo)
IndexAppendToText()
End Sub
Private Sub btnDeleteTBO_Click(sender As Object, e As EventArgs) Handles _
btnDeleteTBO.Click
If tbo_list.Count = 0 Then Exit Sub
Dim ret As String = InputBox _
("Welche Textbox soll gelöscht werden? (0-" & (tbo_list.Count - _
1).ToString & ")",
tbo_list.Count - 1.ToString)
If String.IsNullOrWhiteSpace(ret) Then Exit Sub
Dim index As Integer
If Not Integer.TryParse(ret, index) OrElse
(index < 0 Or index >= tbo_list.Count) Then Exit Sub
'Löshen eines Controls, das über die Liste referenziert wird
RemoveHandler tbo_list(index).KeyDown, AddressOf tbo_keydown 'Demo
tbo_list(index).Dispose() 'Windows Control am Index freigeben
tbo_list(index) = Nothing 'Referenz aufheben, dadurch Net-Rahmen für
' GC freigeben
tbo_list.RemoveAt(index) 'Listenindex löschen
If tbo_list.Count > 0 Then
'Textboxen im Formular neu anordnen
For i As Integer = 0 To tbo_list.Count - 1
tbo_list(i).Top = getTextBox_Top(i)
Next i
End If
'Indices neu eintragen und anzeigen (Demo)
IndexAppendToText()
Me.Refresh()
End Sub
Private Function getTextBox_Top(index As Integer)
Return index * 30 + 80
End Function
Private Function getTextbox_Name()
'Eindeutigen Namen für das Controls ermitteln
Dim index, maxindex As Integer
For i As Integer = 0 To tbo_list.Count - 1
Dim parts() As String = tbo_list(i).Name.Split("_"c)
If Integer.TryParse(parts(parts.Length - 1), index) Then
maxindex = Math.Max(maxindex, index)
End If
Next i
Return "tbo_" & (maxindex + 1).ToString
End Function
Private Function IndexAppendToText()
'Demo-Beispiel Listenindex in Text eintragen
For i As Integer = 0 To tbo_list.Count - 1
tbo_list(i).Text = tbo_list(i).Name & " Index_" & i.ToString
Next i
End Function
Private Sub tbo_keydown(sender As Object, e As KeyEventArgs)
'Bearbeitung des KeyDown-Events aller Textboxen
Dim tbo As TextBox = DirectCast(sender, TextBox)
Me.Text = tbo.Text 'Demo
End Sub
End Class |