Reputation: 3843
When ever I click on Tool strip menu it displays new form every time.I want to stop it displaying the same form again and again. In the code given the form2 is displaying again and again. I want to stop it so it displays once.
Like :
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.MdiParent=this;
f.Show();
}
Upvotes: 2
Views: 165
Reputation: 39132
Another approach would be to declare a variable of type Form2 at class level:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Form2 f2 = null;
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (f2 == null || f2.IsDisposed)
{
f2 = new Form2();
f2.MdiParent = this;
f2.Show();
}
else
{
if (f2.WindowState == FormWindowState.Minimized)
{
f2.WindowState = FormWindowState.Normal;
}
f2.Activate();
}
}
}
Upvotes: 2
Reputation: 67898
You should be able to do something like this:
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
var f2 = this.MdiChildren.OfType<Form2>().FirstOrDefault();
if (f2 != null)
{
f2.Show();
return;
}
Form2 f = new Form2();
f.MdiParent=this;
f.Show();
}
This will show the form if it already exists, otherwise create it and show it.
Upvotes: 3