删除动态添加的文本框 (VB.Net)

Remove textbox that added dynamically (VB.Net)

我正在尝试通过 Button_Click 事件 在我的表单中删除一个 TextBox 控件 (动态添加)(我也动态添加) 但我找不到确切的方法。单击 LinkLabel 时,我的文本框将与按钮控件 (删除按钮) 一起添加。因此,当动态添加时,我的 textbox.name 将像 textbox_1textbox_2textbox_3 并且与它们一起是一个 Button 控件,如 btnDel1btnDel2 ,btnDel3(都放在一个Panel控件中).

我的编码是这样的:

Private Sub Button_Click(sender As Object, e As EventArgs)
    Dim button As Button = TryCast(sender, Button)
    Dim textbox As TextBox = TryCast(sender, TextBox)

    'In this case when btnDel1 is clicked, textbox_1 will be removed as well
    If button.Name = "btnDel1" Then
        PanelOthers.Controls.Remove(button)
    End If
End Sub

按钮已成功删除,但如何删除文本框呢?提前致谢。

有几种方法可以做到这一点:

  1. 将所有相关控件附加到删除按钮的标签 属性。
  2. 创建一个封装按钮和文本框的用户控件。

选项 1:标签 属性

创建控件时,将关联的控件添加到按钮的 .Tag 属性:

Dim button As Button = New Button
Dim textbox As TextBox = New TextBox

button.Tag = {textbox}
'  Add the button and textbox to the UI surface

现在,当单击该按钮时,您可以遍历关联的控件并将它们也删除:

For Each item As Control In button.Tag
    item.Dispose()
Next
button.Dispose()

选项 2:用户控件

这不是教程网站..但您可以对此进行自己的研究。