Error when attempting to Close a form

I get the following error:

**************
An unhandled exception of type 'System.InvalidOperationException' occurred in system.windows.forms.dll

Additional information: Cannot call Close() while doing CreateHandle().
**************

When executing the following code after frm2 opens and the user simply presses the Cancel
button to close the dialog form which also should close the calling form (frmAssembly).

In other words there is no way to continue with frmAssembly form without logging in.


    Private Sub frmAssembly_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim frm As New frmMain
        sqlConn.ConnectionString = frm.sqlConn.ConnectionString
        frm = Nothing
        gstrProdTrkNo_Prev = "0"
        Dim frm2 As New frmGrpLogOn
        frm2.ShowDialog()
        Select Case frm2.DialogResult

            Case DialogResult.OK
                With Me
                    intGrp_ID = frm2.Grp_ID
                    .tbGrpName.Text = frm2.GrpName
                    dtLogInDT = frm2.GrpLogInDT
                    .rbDone.Checked = True
                    .tbProdTrkNo.Focus()
                End With
            Case DialogResult.Cancel
                Me.Close()  '<--ERROR OCCURS ON THIS LINE
                Exit Sub
        End Select


    End Sub
</code


Answer this question

Error when attempting to Close a form

  • rajuraju

    That sounds like the best way to handle it. 

  • vivi_0606

    Open Event

    There is no open event in Windows .NET using VB.NET.

  • NewDBA

    I haven't tried it, but maybe you can move all this code to the Open event instead of Load.
  • pongopiprakash

    Excellent,  I don't know why I didn't think of that.

    Actually the frmAssembly is a child form in a midi application which is opened from a menu item on the main form.  So I just move this code to the menu item click event.  If the user cancels the dialog form, I simly do not show frmAssembly.

    Apparemtly the root problem is that attempting to close the form in Load process errors because the Close event has not been formed yet   Whatever happened the to "Open" event which was cancellable.


  • raindrops123

    It looks like the best way to do this is to create a main function in your VB app.  Create the Form2, check the dialog result and then determine whether or not to create and show Form1.  


    http://msdn.microsoft.com/library/default.asp url=/library/en-us/vbcn7/html/vbconHelloWorld.asp

    Something along the lines of...

        Shared Sub Main()
            Dim form2 As Form2
            form2 = New Form2()

            If (form2.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
                Application.Run(New Form1())
            End If
        End Sub

  • Error when attempting to Close a form