Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

what is the cause of this error?

Back to Forum: Tech Off
  • User profile image
    Shark_M

    For Each frm As Form In My.Application.OpenForms
          If frm.Name.ToString() <> "frmC" Then
                If frm.InvokeRequired = True And frm.Name = "frmS" Then
                            Dim s As New frmSignOn.CloseMe(AddressOf frm.Close)
                            Me.Invoke(s)
                        Else
                            frm.Close()
                            frm.Dispose()
                        End If
                    End If
                  Next
    InvalidOperationException was unhandled

    Collection was modified; enumeration operation may not execute.



    Error Occured At Next line

  • User profile image
    Shark_M

    Dim FrmCol = My.Application.OpenForms
    For Each frm As Form In FrmCol
          If frm.Name.ToString() <> "frmC" Then
                If frm.InvokeRequired = True And frm.Name = "frmS" Then
                            Dim s As New frmSignOn.CloseMe(AddressOf frm.Close)
                            Me.Invoke(s)
                        Else
                            frm.Close()
                            frm.Dispose()
                        End If
                    End If
                  Next

    the error was NOT gone

  • User profile image
    Shark_M

    For Each frm As Form In My.Application.OpenForms
          If frm.Name.ToString() <> "frmC" Then
                If frm.InvokeRequired = True And frm.Name = "frmS" Then
                            Dim s As New frmSignOn.CloseMe(AddressOf frm.Close)
                            Me.Invoke(s)
                        Else
                            frm.Close()
                            frm.Dispose()
                        End If
                    End If
                        if My.application.openforms.count = 1 then exit for
                  Next

    I added the If line before the Next, and it seemed to solve the error


    is there a better way to resolve this error?

  • User profile image
    JohnAskew

    Collections are read only when iterating through them with foreach.

    Use a for loop instead and you can edit the objects at will.


  • User profile image
    Jorgie

    Yep, I think JA called it...

    You have to be careful what you modify while walking a collection using foreach!

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.