2012-11-23 48 views
0

我有一個TableLayoutPanel(有一行,三列),它放在窗體的Panel控件內。如何在VB.Net窗口應用程序中定位動態創建的控件?

我的表單也有一個命令按鈕。每次單擊按鈕時,都會動態創建標籤(第一列),文本框(第二列)和按鈕(第三列)。

我要像下面進行操作:

當我點擊按鈕(在每行的第三列),然後LABEL+TEXTBOX+BUTTON關注行必須同時留下的是其他控件被刪除。

有人能幫我解決嗎?

回答

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 

這將讓你用設計師來設計一行,你也可以在小的「行控制」內編寫所有的功能(如驗證等),這將使你的代碼更清潔。

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 
相關問題