Reputation: 507
I have a form(MdiParent) with the following code:
public partial class Main : Form
{
Form1 frm1 = null;
Form2 frm2 = null;
}
With a couple of menus I do the following:
private void toolStripMenuItem_ClickForm2(object sender, EventArgs e)
{
if(frm2 == null)
{
frm2 = new Form2(frm1);
frm2.MdiParent = this;
}
frm2.Show();
}
private void toolStripMenuItem_ClickForm1(object sender, EventArgs e)
{
if(frm1 == null)
{
frm1 = new Form1();
frm1.MdiParent = this;
}
frm1.Show();
}
If I click menuitemForm2 do some operations(DB access and populate a DatagridView, frm1 is never initialized in frm2) in form2 and then click menuitemForm1 in order to show frm1. It is going to produce two windows of the same form1.
Does anyone have faced this strange behaviour before?
Addendum because of the comments...
frm2 does something like this with frm1:
Form1 frm ;
public Form2(Form1 form1)
{
frm = form1;
}
public void Optionalmethod()
{
if(frm == null)
{
frm = new Form1();
frm.MdiParent = this.MdiParent;
}
frm.Show();
}
Optionalmethod()
is not executed during the testing.
According to my logic form1 can be initialized in two cases:
1. Inside form2
2. In the Main form
For me does not matter where form1 is initialized, but it is important to have only one instance of it. Thats is the reason because I decided to pass the reference even if it is null
Upvotes: 0
Views: 70
Reputation:
I have been unable to replicate your problem, but I would suggest an alternative in any case. I am not personally in favour of passing around form variables between child forms. There is a much neater way to do it. Replace your code with
private void toolStripMenuItem_ClickForm1(object sender, EventArgs e)
{
ShowForm1();
}
public void ShowForm1()
{
try
{
if (frm1 == null)
{
frm1 = new Form1();
frm1.MdiParent = this;
}
else if (frm1.MdiParent == null)
{
frm1 = new Form1();
frm1.MdiParent = this;
}
frm1.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Please note the extra else if. If a form has been created and closed, the reference is not null, but its MdiParent property will be null.
Now remove the Form1 parameter in the Form2 constructor (plus the private member) and replace the OptionalMethod code with:
var parent = (MainForm)this.MdiParent;
parent.ShowForm1();
This should work fine.
HTH
Jonathan
Upvotes: 1