开发者

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 ob开发者_如何学Cject ..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.

E.g. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜