如何在VB.Net windows应用程序中找到动态创建的控件?

时间:2012-11-23 11:51:15

标签: vb.net visual-studio-2010 visual-studio

我有一个TableLayoutPanel(有一行,三列),它放在表单上的Panel控件中。

我的表单也有一个命令按钮。每次单击该按钮时,将动态创建标签(在第一列中),文本框(在第二列中)和一个按钮(在第三列中)。

我想执行如下操作:

当我单击按钮(在每行的第三列中)时,必须删除相关行的LABEL+TEXTBOX+BUTTON,同时保留其他控件。

有人可以帮我解决吗?

2 个答案:

答案 0 :(得分:0)

我建议您创建自己的用户控件,其中包含所有3个元素(标签,文本框,按钮),并在每次单击主按钮时添加此控件。然后,您可以将事件处理程序连接到单击“行”控件上的按钮,并从主窗体中处理它。下面的通用想法:

在您的用户控件中,您需要添加:

Public Event MyButtonClicked

Public Sub MyButtonClick() Handles MyButtonClick
    Raise Event MyButtonClicked(Me)
End Sub

在主表单上你会有类似的东西

Public Sub CreateNewRow() Handles MainButton.Click
    Dim NewRow as New MyUserControl
    AddHandler NewRow.Click, AddressOf RemoveRow
    FlowLayoutPanel.Controls.Add(NewRow)
End Sub

Public Sub RemoveRow(ByRef Row as MyUserControl)
    FlowLayoutPanel.Controls.Remove(Row)
End Sub

这将允许您使用设计器设计一行,您还可以在小“行控制”中编写所有功能(如验证等),这将使您的代码更清晰。

答案 1 :(得分:0)

您需要点击按钮

引用其他两个控件

我的建议---

'craete a class to hold all controls in single object
Public Class MyCtls
    Public mLBL As Label
    Public mTXT As TextBox
    Public mBTN As Button

    Public Sub New(ByVal LBL As Label, ByVal TXT As TextBox, ByVal BTN As Button)
        MyBase.New()
        mLBL = LBL
        mTXT = TXT
        mBTN = BTN
    End Sub
End Class

'While creating new row create class reference and store it somewhere in accessed control
'For example we are using tag prosperity of button for this
'Now add handler for this button
Private Sub CreateNewRow()
    Dim nRow As MyCtls = New MyCtls(New Label, New TextBox, New Button)
    'set postition and add to parrent
    nRow.mBTN.Tag = nRow
    AddHandler nRow.mBTN.Click, AddressOf mBTN_Click
End Sub

'now for removing this row
Private Sub mBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim thisRow As MyCtls = DirectCast(CType(sender, Button).Tag, MyCtls)
    'remove handler first
    RemoveHandler thisRow.mBTN.Click, AddressOf mBTN_Click

    'remove controls from its parent and dispose them
    yourparentcontrol.Controls.Remove(thisRow.mLBL)
    yourparentcontrol.Controls.Remove(thisRow.mTXT)
    yourparentcontrol.Controls.Remove(thisRow.mBTN)

    'dispose them all
    thisRow.mLBL.Dispose() 'do as this
End Sub