Menustrip that lists the forms mdi son, almost finished

0

Hello, how are you? I am trying to make a ready of the children MDI forms, open of the current form (Parent), the code is simple, add items when a new child form is added, but when you delete it and execute the code again, execute the following error:

  

"An exception of type 'System.InvalidOperationException' occurred   in mscorlib.dll but not controlled in the user code

     

Additional information: Modified collection; it may not run   the enumeration operation. "

The code is as follows:

For Each frm In Me.MdiChildren
            If VentanasToolStripMenuItem.DropDownItems.Count > 0 Then
                For Each item As ToolStripItem In VentanasToolStripMenuItem.DropDownItems
                    If TypeOf (item) Is ToolStripMenuItem Then
                        If item.Text.Substring(0, 2) = "- " And item.Text.Substring(2) <> frm.Text Then
                            Dim menuventana As New ToolStripMenuItem() With {.Text = "- " & frm.Text, .Name = frm.Name}
                            VentanasToolStripMenuItem.DropDownItems.Add(menuventana)
                        End If
                    End If
                Next
            Else
                Dim menuventana As New ToolStripMenuItem() With {.Text = "- " & frm.Text, .Name = frm.Name}
                VentanasToolStripMenuItem.DropDownItems.Add(menuventana)
            End If
        Next
        'quitar los sobrantes
        If VentanasToolStripMenuItem.DropDownItems.Count > 0 Then
            For Each item As ToolStripItem In VentanasToolStripMenuItem.DropDownItems
                If TypeOf (item) Is ToolStripMenuItem Then
                    If item.Text.Substring(0, 2) = "- " Then
                        Dim encontrado As Boolean = False
                        For Each frm In Me.MdiChildren
                            If frm.Text = item.Text.Substring(2) Then
                                encontrado = True
                            End If
                        Next
                       If Not encontrado Then VentanasToolStripMenuItem.DropDownItems.Remove(item)
                    End If
                End If
            Next
        End If

Runs in the "WindowsToolStripMenuItem.DropDownOpening" event Does anyone find the problem? because I do not understand, for me the code is correct, I hope response! thanks

    
asked by Bernardo Harreguy 16.09.2017 в 16:51
source

1 answer

0

I do not like the instruction "For Each frm In Me.MdiChildren". Although it may seem like it, it does not refer to a constant list. Each time a loop is made, the Me.MdiChildren list is recalculated, which can be a source of errors. I would write:

Dim WindowList = Me.MdiChildren 'This is how the MdiChildren method is calculated once, not every loop loop.

For Each frm In listaVentanas 'Instructions. Next

    
answered by 16.09.2017 в 17:56