简体   繁体   中英

c# winform programming

I have two forms; one called 'win' and the other called 'loss'. There is a button on 'win' form which displays the 'loss' form. When this button is clicked both forms are visible. When I close the 'loss' form and then click the button on the 'win' form again I get the following exception:

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

Please could someone point me in the right direction so I can resolve this?

It is because your 'loss' form is already closed and has been disposed, so it cannot be used anymore. You need to create a new instance of the form, like so (don't know how exactly your code looks):

this.loss = new LossForm(); 
this.loss.Show();

You can verify IsDisposed property of form, before referencing it.

Eg button click handler on 'win' form:

if (loss.IsDisposed)
  return;

// do stuff with loss form

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

  1. You can run 'loss' form as Dialog. And read all needed properties after dialog closed.
  2. You can subscribe to 'loss' form events and process them in 'win' form.

It's not a very good model your going for but you could hook into the formClosing event, cancel it and then hide the form instead. That means the form wont be automatically disposed and you could call show again.

Put some time aside to research MVC architecture - it looks complicated at first, but it really does help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM