0

I have a button in form1 that opens form2. I do this using frm2.show(). It works totally fine for the first time that I open frm2, but when I close frm2 and click on the button in frm1 to open frm2 again, I get this error:

enter image description here

Can someone tell me how to solve it?

Edit: I have a module where I have my database connection and my declaration for the forms:

Public frmGame As New Game
Public frmPlay As New Play
Public frmFinish As New GameFinish
Public frmLogin As New Login
Public frmManage As New Manage
Public frmInsert As New Toevoegen

Where I open the form is just when I click on a button in form1.

Elomar Adam
  • 251
  • 1
  • 15

1 Answers1

4

Sounds to me like you are Close()ing frm2. Closing a form should dispose it and release its resources, so you can't simply Show() it again. Instead, you need to create a new instance of the object, like this:

frm2=new Form2()
frm2.Show()

If that doesn't work (perhaps because you don't want to re-initialize the form's data members), you could use Hide(), rather than Close() to temporarily hide the form during your program's execution.

If you need to prevent the form from being closed with the X button, you can do this with a few different methods:

  1. The best way to go may be to hide or disable the close button. Read up on This post to get a better idea of how to do that.

  2. You can use the FormClosing event, either from inside frm2 or from the main window. Set the Cancel property on the FormClosingEventArgs object that gets passed in. The problem here is that you will need to provide an additional code path to close the form when you actually want it to close. The CloseReason property of the FormClosingEventArgs object should give you a way to handle that properly. Needless to say, this is probably the riskiest way to do things, since you need this window to close when the application shuts down, but you're also intentionally block that from happening.

  3. You could catch the FormClosed event in the the form that spawns frm2, then create a new instance of the window. Again, you'll need to provide a code path to allow the window to close when the application shuts down.

In all, method 1 is probably the safest. You can close the window with .Close() when the application shuts down, but the user can't close it with the X button.

Community
  • 1
  • 1
Tom Wilson
  • 99
  • 3