SOAMad SOAMad - 2 years ago 114 Question

Opening Single Child form at a time in VB.NET MDI form

I am trying to keep only one active child at a time. I want to dispose other child when opening any child in MDI form.
I have tried many possible way without luck. It would be nice to have a separate class function to do the dirty work. Any help will be highly appreciated.
Here is the sample code form class:

Imports System.Reflection

Class closeHelper

Public Shared Sub HideAllForms()
Dim currentAssembly As Assembly = Assembly.GetExecutingAssembly()
Dim count As Integer = Application.OpenForms.Count
For i As Integer = 0 To count - 1 Step +1
Dim f As Form = Application.OpenForms(i)
If f.[GetType]().Assembly Is currentAssembly AndAlso f.Name <> "frmMDI" Then 'Here 'frmMDI' is the name of mdiform.
End If
End Sub

End Class

Answer Source

One should always use a reverse loop when deleting or doing an action that will modify the collection.

For i As Integer = (count - 1) To 0 Step -1

Picture this (a collection of 3 items) using a forward loop:

  1. iteration: Delete/close index 0, indices available: 0, 1, 2, Result: OK.
  2. iteration: Delete/close index 1, indices available: 0, 1, Result: OK.
  3. iteration: Delete/close index 2, indices available: 0, Result: Error.

As you can see, the last will throw an IndexOutOfRangeException.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download