0

I'm trying to open a new window form on a button click

In main program's constructor I've got:

form_targeting = new Targeting();

In button1_Click(...) there is:

form_targeting.Show();

and ofc in main program's fields there's

public static Targeting form_targeting;

When opening first time, It works correctly. After closing 2nd window and pressing the button in a 1st window again, I get error:

Cannot access a disposed object. Object name: 'Targeting'.

I've added that into Targeting class but it still doesn't work:

        private void Targeting_FormClosing(Object sender, FormClosingEventArgs e)
            {
                this.Hide();
                e.Cancel = true;
            }

It works now, I had to write completely the same but using designer :p thanks guys :)

4

3 回答 3

2

将代码放入按钮单击事件中。

button1_Click(...)
{
   form_targeting = new Targeting();
   form_targeting.Show();
}

结束关闭表格

form_targeting.Close();
于 2012-04-30T11:10:31.263 回答
1

关闭表单调用Dispose它。您需要为FormClosing事件编写一个处理程序。在该事件处理程序中调用Hide您的表单实例并设置e.Cancel = true为不关闭表单。

于 2012-04-30T11:13:42.527 回答
1

下面的代码意味着,您正在初始化 Targeting 的实例。

 form_targeting = new Targeting();

一旦您使用以下代码显示表单form_targeting.Show();并通过单击十字按钮或以任何方式关闭表单。以第一种形式初始化为 form_targeting 变量的内存被释放。

所以第二次,您尝试打开相同的表单,它会引发错误。

于 2012-04-30T11:16:09.797 回答