2013-10-23 43 views
0

我正在創建並通過單擊button1來顯示一組表單。然後我需要點擊button2關閉所有這些表單。如何讓VB.Net通過標記值關閉一組表單

通過事件的button1_Click:

Dim frm As New myfrm() 

frm.Tag = "temptag" 

frm.TopLevel = False 

controls.add(frm) 

通過事件button2_Click:

接近任何形式的地方tag = "temptag"

如何創建代碼,將做到這一點?

+0

查看我更新的代碼波紋管。我測試了它,它工作。 – Tarik

回答

2

下面的代碼會做你想要什麼,而無需使用標籤:

Public Class Form1 
    Private ChildNumber As Integer = 0 
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
     Dim frm As New Form1 
     ChildNumber += 1 
     frm.Text = "Child Form " & ChildNumber 
     frm.Show() 
     frm.TopLevel = False 
     Me.Controls.Add(frm) 
     frm.Tag = "temptag" 
    End Sub 

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click 
     Dim count As Integer = Me.Controls.Count 
     For i As Integer = Me.Controls.Count - 1 to 0 Step -1 
      Dim ctrl As Control 
      ctrl = Me.Controls(i) 
      If ctrl.Tag = "temptag" Then 
       DirectCast(ctrl, Form1).Dispose() 
      End If 
     Next 
    End Sub 
End Class 
+0

儘管While循環沒有贏得任何獎品的清晰度。只需使用For As As Integer = Me.Controls.Count-1至0 Step -1。使用Dispose()而不是Close()。 –

+0

@HansPassant感謝Hans。將在我的電腦上修復代碼。 – Tarik

+0

修復了我的代碼,按照Hans Passant的建議向後循環。 – Tarik

1

添加以下內容:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 

    For x As Integer = Me.Controls.Count - 1 To 0 Step -1 
     Dim Ctrl As Control = Me.Controls(x) 
     Try 
      If Ctrl.Tag = "temptag" Then 
       Ctrl.Dispose() 
      End If 
     Catch ex As Exception 

     End Try 
    Next 

End Sub 

編輯:

更新for循環通過控件集合向後步驟(從而不遺漏任何控制 - 感謝@Tarik),並改變.Close.Dispose爲每@Hans帕桑特奉勸塔裏克

+0

您無法在Controls集合中添加創建的表單。 – Tarik

+0

@Tarik,如果你設置窗體的Toplevel = false,你可以將窗體添加到另一個窗體的控件集合 – Grahamvs

+0

不知道。謝謝! – Tarik