迭代打开表单并仅关闭特定表单

时间:2014-07-21 12:13:43

标签: c# vb.net winforms openform

  • 以下是我写的代码

    Private Sub CloseTransactionForms()
      Dim ActiveFroms As New List(Of String)
      Dim formToClose As New List(Of Form)
      Dim j As Integer
      ActiveFroms.Add("FrmSale")
      ActiveFroms.Add("FrmpPurchase")
      ActiveFroms.Add("FrmSaleReturn")
      ActiveFroms.Add("FrmPurchaseReturn")
        Try
          For Each frm As Form In My.Application.OpenForms
            For j = 0 To ActiveFroms.Count - 1
                If frm.Name.ToString() = ActiveFroms.Item(j) Then
                    formToClose.Add(frm)
                End If
            Next
        Next
        If formToClose.Count > 0 Then
            Dim i As Integer
            For i = 0 To formToClose.Count - 1
                Dim xform As Form = formToClose.Item(i)
                xform.Close()
            Next
        End If
      Catch ex As Exception
     End Try
    End Sub
    
  • 此代码将遍历我的应用程序中的打开表单,并从应用程序中关闭已定义的表单

  • 但对我来说似乎不太好(在循环中使用3 for循环,有时在for循环中迭代)我认为会有另一种好的方法,请为我​​建议一个好的解决方案

注意:我已经看过this question in SO

1 个答案:

答案 0 :(得分:2)

您可以使用LINQ查找要关闭的表单,并使用List.ForEach关闭它们:

Dim ActiveFroms = New List(Of String) From {"FrmSale", "FrmpPurchase", "FrmpSaleReturn", "FrmPurchaseReturn"}

Dim formsToClose = From form In My.Application.OpenForms.Cast(Of Form)()
                   Join activeFormName In ActiveFroms
                   On form.Name Equals activeFormName
                   Select form

formsToClose.ToList().ForEach(Sub(form) form.Close())

您无法在上面的查询中使用For Each,因为Form.Close会修改集合which is not allowed。因此我使用List.ForEach