0

我正在通过单击 button1 创建并显示一组表单。然后我需要点击 button2 来关闭所有这些表单。

按事件 button1_Click:

Dim frm As New myfrm()

frm.Tag = "temptag"

frm.TopLevel = False

controls.add(frm)

按事件 button2_Click:

关闭任何表格tag = "temptag"

如何创建可以实现这一目标的代码?

4

2 回答 2

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
于 2013-10-23T11:19:48.677 回答
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),并根据@Hans Passant 对 Tarik 的建议更改.Close.Dispose

于 2013-10-23T11:15:11.250 回答