Reputation: 23
I'm opening a MDI child form from another mdi child and it's working, but now I have to close it by the same way and nothing happens.
Here is an example of code i'm using:
private void checkbox1_CheckedChanged(object sender, EventArgs e)
{
Form1 newForm1 = new Form1();
newForm1.MdiParent = this.MdiParent;
if (checkbox1_CheckedChanged.Checked == true)
{
newForm1.Show(); //this is working
}
else
{
newForm1.Dispose(); //this is not working. I have tryed .Close(), .Hide()... unsucessfully.
}
}
Explaining: i have this checkbox1 in a mdi child and when it's checked another mdi child (newForm1) will open, and when it's unchecked this mdi child (newForm1) will close, hide or something like this.
Any suggestions? thanks!
Upvotes: 2
Views: 5513
Reputation: 81675
You need to "find" the form in the form collection in order to dispose of it:
private void checkBox1_CheckedChanged(object sender, EventArgs e) {
if (checkBox1.Checked) {
Form1 form1 = new Form1();
form1.MdiParent = this.MdiParent;
form1.Show();
} else {
Form found = this.MdiParent.MdiChildren.Where(x =>
x.GetType() == typeof(Form1)).FirstOrDefault();
if (found != null) {
found.Dispose();
}
}
}
This assumes there is only one Form1 form in the collection.
The other way to do this is to declare the form variable outside of the check changed method scope:
Form1 form1;
private void checkBox1_CheckedChanged(object sender, EventArgs e) {
if (checkBox1.Checked) {
if (form1 == null || form1.IsDisposed) {
form1 = new Form1();
form1.MdiParent = this.MdiParent;
form1.Show();
}
} else {
if (form1 != null) {
form1.Dispose();
}
}
}
Upvotes: 2
Reputation: 9322
Add a public method in Form1 like:
Public void closeForm()
{
Close();
}
And in the code you have shown instead of
newForm1.Dispose()
It would be:
newForm1.closeForm();
Upvotes: 0