vb.netwinformsopenform

Close all open forms except for some VB.Net


as the title, I am trying to close all open forms except some in VB.Net but the forms don't close. Here is the code I used:

Dim lista As New FormCollection
lista = Application.OpenForms
For Each a As Form In lista
    If Not a.Text = "formLogout" And a.Text = "arresto" And a.Text = "riavvio" And a.Text = "formOpen" Then
        a.Close()
    End If
Next
scrivania.Close()
Me.Close()

Grazie.


Solution

  • If statement will return true when all provided conditions are true, which is not possible because you compare same form.Text with different values.
    Notice that in your example Not will be applied only for the first condition

    You possibly can rewrite condition as follow:

    If Not (form.Text = "formLogout" OrElse form.Text = "arresto") Then ..
    

    Suggest to use a collection of form names, which should not be closed

    Dim remainOpenForms As New HashSet(Of String)
    remainOpenForms.Add("formLogout")
    remainOpenForms.Add("arresto")
    
    ' Create collection of forms to be closed
    Dim formsToClose As New List(Of Form)
    For Each form As Form In Application.OpenForms
        If remainOpenForms.Contains(form.Text) = False Then formsToClose.Add(form)
    Next
    
    For Each form As Form In formsToClose
        form.Close()
    Next