Vb.net – Check if particular instance of form is opened in vb.net 2010

vb.net

In the posted question: "Check if form is opened" the answer below was posted as correct. However, I would like to know how to check if a particular instance of a form is open before opening it; for example, to check if an editing screen of the same record is being opened again, or a form to add a new record, when another form to do the same thing is open already.

Below is the code posted as the correct answer for the original question. Can it be modified to do what I need? Thanks in advance.

If Application.OpenForms().OfType(Of Form2).Any Then

  MessageBox.Show ("Opened")

Else

  Dim f2 As New Form2

  f2.Text = "form2"

  f2.Show()

End If

A particular instance would be a form that is editing a particular record from a table. I would also be tracking the status of the edit (whether the form was in edit mode or not) Or, if this form has a child (a form that edits a sub table of this record); the parent form cannot exit until the child is closed.

I currently create a tree of open forms, their name, the record they are editing, and the edit status, and their closing is updated in the tree. Answer # 2 at first glance seems like it could handle these situations and there would be no need to have this data structure in the background that needs to be constantly updated whenever an action is taken. It might be possible to make it more general so it could be reused easily from application to application.

Best Solution

Yes, this can easily be modified to do what you are looking for.

You need to add a public property called Key (or whatever you want) to Form2 and then you can use the ShowOrOpenForm method below to accomplish your goals:

Public Sub ShowOrOpenForm(sKey As String)

    If ShowFormForKey(sKey) Then
        MessageBox.Show("Opened")
    Else
        Dim f2 As New Form2

        f2.Key = sKey
        f2.Text = "form2"
        f2.Show()
    End If
End Sub

Private Function ShowFormForKey(sKey As String) As Boolean

    For Each oForm As Form2 In Application.OpenForms().OfType(Of Form2)()
        If oForm.Key = sKey Then
            oForm.Show()
            Return True
        End If
    Next

    Return False
End Function
Related Question