打开然后关闭并再次打开新表单时出现未处理的异常
我收到 ObjectDisposeException was unhandled
,并显示消息 Cannot access a Dispose object.
当在类的开头通过 MyForm myForm = new 初始化此子表单时,会发生这种情况MyForm();
然后通过 myForm.txtBox.AppendText("Text");
添加一些文本到该表单的文本框中,然后使用一些打开我的新表单带代码的按钮myForm.Show();
。现在,当我的工作完成后,我可以关闭表单。现在,当我想再次显示数据时,我遇到了该异常。
我想将文本框的内容保留在新表单中,但似乎存在一个问题,即我尚未处理其中的所有内容。
如何避免这种情况,以便我可以在按下按钮时随时查看新的表单内容?
I'm getting ObjectDisposedException was unhandled
with message Cannot access a disposed object.
This happens when initialize this child form at the beginning of my class by MyForm myForm = new MyForm();
and then adding some text to my text box of that form by myForm.txtBox.AppendText("Text");
and then opening my new form my form by using some button with code myForm.Show();
. Now when my job is done I can close the form. Now, when I want to display the data again I'm getting that exception.
I want to keep the content of text box in my new form, but it seems like there is a problem that I haven't disposed everything in it.
How to avoid this so I can view the new forms content any time I press button?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自
Form.Close 上的 MSDN 文档
:
您可以捕获表单上的
Form.Closing
事件,取消该事件,然后隐藏表单而不是关闭
它。From the MSDN documentation on
Form.Close
:You could capture the
Form.Closing
event on the form, cancel the event, and hide the form instead ofClose
ing it.问题似乎是您在类的开头创建了一个
MyForm
实例,并在每次按下按钮时重新使用它。不幸的是,这是行不通的。表格关闭后将被丢弃,因此不再有效。下次您尝试显示它时它会抛出。解决此问题的最简单方法是完全在按钮单击事件中创建并显示表单。不要在点击之间重复使用它的实例。
如果您需要在两次点击之间保留某种状态(例如文本),则存储该状态,但不存储
Form
实例。The problem appears to be that you're creating an instance of
MyForm
at the start of the class and re-using it every time the button is pressed. That won't work unfortunately. Once the form is closed it will be disposed and hence no longer valid. It will throw the next time you try and show it.The easiest way to work around this is to create and display the form entirely within the button click event. Don't reuse it's instance between clicks.
If there is some state you need to keep between clicks, such as the text, then store that but not the
Form
instance.您应该像 M.Babcock 所说的那样捕获 FormClosing 事件,但我还建议您检查关闭原因,如果用户请求它,您可以取消并执行您想要的任何操作:private
否则您将无法关闭它如果你愿意的话。
You should capture the FormClosing event as M.Babcock said but I'd also recommend you to check the close reason, if te user requested it, you can cancel and do whatever you want:private
Otherwise you won't be able to close it in case you want to.