【问题标题】:Remove textbox that added dynamically (VB.Net)删除动态添加的文本框(V​​B.Net)
【发布时间】:2016-01-26 03:11:45
【问题描述】:

我正在尝试通过Button_Click 事件(我也动态添加)在我的表单中删除TextBox 控件(动态添加),但我不能找到确切的方法来做到这一点。单击LinkLabel 时,我的文本框将与按钮控件(删除按钮) 一起添加。因此,当动态添加时,我的 textbox.name 将像 textbox_1,textbox_2,textbox_3 并且与它们一起是像 btnDel1,btnDel2,btnDel3 这样的按钮控件(全部放置在面板控件中) .

我的编码是这样的:

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

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

【问题讨论】:

    标签: vb.net winforms textbox


    【解决方案1】:

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

    1. 将所有相关控件附加到删除按钮的 Tag 属性。
    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:用户控件

    所以不是一个教程网站.. 但你可以自己研究这个。

    【讨论】:

    • 使用Tag 属性效果很好。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多