C # winform programming

I have two forms; one is called a win, and the other is called a loss. In the β€œwin” form, there is a button that displays the β€œloss” form. When this button is pressed, both forms are visible. When I close the "loss" form and then click the "win" button again, I get the following exception:

An unhandled exception has occured: Unable to access a disposed object ..object :form

Please can someone point me in the right direction so that I can solve this?

+4
source share
3 answers

This is because your β€œloss” form is already closed and deleted, so it can no longer be used. You need to create a new instance of the form, for example (I don’t know what your code looks like):

 this.loss = new LossForm(); this.loss.Show(); 
+4
source

You can check the IsDisposed property of a form before referencing it.

eg. button click handler in the form of 'win':

 if (loss.IsDisposed) return; // do stuff with loss form 

Update: I think it’s better not to share control between the forms.

  • You can run the "loss" form as a "Dialog". And read all the necessary properties after closing the dialog box.
  • You can subscribe to events of the "loss" form and process them in the "win" form.
+1
source

This is not a good model you are going for, but you can hook into the formClosing event, cancel it, and then hide the form. This means that the form will not be automatically deleted, and you can call up the show again.

Spend some time exploring the MVC architecture - at first it looks complicated, but it really helps.

0
source

Source: https://habr.com/ru/post/1336787/


All Articles