2014-01-14 80 views
0

enter image description here如何在VB.NET中管理動態創建的控件?

我才明白如何使動態控制在VB.NET(我的意思是,只需要添加一個新的組成部分)

但是,與VB6,似乎很難處理這些動態的東西。

當我點擊DONE按鈕時,我想讓數組填充文本框的文本。

與此同時,我想創建一個刪除按鈕,刪除按鈕本身和同一行中的文本框。

有沒有簡單的方法或示例代碼?

謝謝!

+1

它很大程度上取決於您如何創建動態控件以及在哪裏存儲引用。我建議顯示創建控件的代碼。 – Steve

回答

1

在表單上放置一個名爲pnlLayout的TableLayoutPanel,並添加名爲btnAdd的添加按鈕。配置TableLayoutPanel有兩列,根據需要調整列寬。

粘貼下面的代碼到您的形式:

Public Class Form1 
    Dim deleteButtons As List(Of Button) 
    Dim textBoxes As List(Of TextBox) 

    Sub New() 
    ' This call is required by the designer. 
    InitializeComponent() 

    ' Add any initialization after the InitializeComponent() call. 
    deleteButtons = New List(Of Button) 
    textBoxes = New List(Of TextBox) 
    End Sub 

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click 
    Dim elementCount As Integer = deleteButtons.Count 

    Dim txt As New TextBox 
    txt.Width = 100 
    txt.Height = 20 
    textBoxes.Add(txt) 

    Dim btn As New Button 
    btn.Width = 100 
    btn.Height = 20 
    btn.Text = "Delete " & elementCount.ToString 
    AddHandler btn.Click, AddressOf btnDelete 
    deleteButtons.Add(btn) 

    pnlLayout.SetCellPosition(txt, New TableLayoutPanelCellPosition(0, elementCount)) 
    pnlLayout.SetCellPosition(btn, New TableLayoutPanelCellPosition(1, elementCount)) 

    pnlLayout.Controls.Add(btn) 
    pnlLayout.Controls.Add(txt) 
    End Sub 

    Private Sub btnDelete(sender As Object, e As EventArgs) 
    Dim senderButton As Button = DirectCast(sender, Button) 
    Dim txt As TextBox = textBoxes(deleteButtons.IndexOf(senderButton)) 
    pnlLayout.Controls.Remove(senderButton) 
    pnlLayout.Controls.Remove(txt) 
    End Sub 

End Class 

默認情況下,它不會有任何文本框和無Delete按鈕,你可以添加「文本框+刪除按鈕」,只要你想盡可能多的行。當您按Delete時,該行將被刪除(並且所有內容都被移動以容納空白空間)。

0

對於textbox'ex部分:

Dim strcol() As String = {TextBox2.Text, TextBox3.Text} 
    For Each strtxt In strcol 
     MessageBox.Show(strtxt) 
    Next 

這真的取決於你的代碼,但是,如果你有他們的名字用它來刪除按鈕&/textbox'es:

For i As Integer = Me.Controls.Count - 1 To 0 Step -1 
     If TypeOf Me.Controls(i) Is TextBox Then 
      If Me.Controls(i).Name = "TextBox2" Then 
       Me.Controls.RemoveAt(i) 
      End If 
     End If 
     If TypeOf Me.Controls(i) Is Button Then 
      If Me.Controls(i).Name = "Button3" Then 
       Me.Controls.RemoveAt(i) 
      End If 
     End If 
    Next 

但這取決於您的代碼...