Reputation: 3152
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 :)
Upvotes: 0
Views: 141
Reputation: 20745
The below code means, you are initializing a instance of Targeting from.
form_targeting = new Targeting();
Once you show the form using following code form_targeting.Show();
and close the form by clicking on the cross button or in any way. The memory initialize to form_targeting variable in first form is get freed.
So second time, you try to open same form, it raises error.
Upvotes: 1
Reputation: 2884
Closing the form calls Dispose
on it. You need to write a handler for the FormClosing event. In that event handler call Hide
on your form instance and set e.Cancel = true
so that the form is not closed.
Upvotes: 1
Reputation: 4546
Put the code into button click event.
button1_Click(...)
{
form_targeting = new Targeting();
form_targeting.Show();
}
End close form by
form_targeting.Close();
Upvotes: 2