Search code examples
c#vb.netwinformsopenform

iterate through open forms and close particular forms only


  • given below is the code i wrote

    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
    
  • this code will iterate through the open forms in my application and close the defined forms from the application

  • but it seems not good for me (using 3 for loops in it and it took sometimes while iterating via for loop) i think there will be another good method, please suggest a good solution for me

Note : i have already seen this question in SO


Solution

  • You can use LINQ to find the forms you want to close and List.ForEach to close them:

    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())
    

    You cannot use a For Each with the query above because Form.Close will modify the collection which is not allowed. Therefore i use List.ForEach.