tags:

views:

47

answers:

5

I have the code:

private void Button1_Click (object sender, EventArgs e)
(
    Form2 f2 = new Form2 ();
    f2.Show ();
)

how to make so that Form2 when you click on Button1 not opened for the second time, if it is open?

sorry for bad english

+1  A: 

Assuming your main form class is MyForm, update your code as below. The idea is to maintain only single instance of the Form2.

public partial class MyForm: Form
{
    public MyForm()
    {
        InitializeComponent();
    }

    private Form2 f2;
    private void Button1_Click (object sender, EventArgs e)
    (    
        if (null == f2 || f2.IsDisposed)
            f2 = new Form2();

        f2.Show ();
    )
}
this. __curious_geek
+2  A: 

You have to make sure you only have 1 instance of Form2 created. One way to do this is to move the object declaration and instantiation to a private variable and in your click event handler simply call the Show() method:

private Form2 f2 = new Form2();
private void Button1_Click (object sender, EventArgs e)
(
    if(f2 == null) 
    {
      f2 = new Form2();
    }
    f2.Show ();
)
Oded
when I close form2 and then try to open, error: access to the object can not be disposed of
Saska
@Saska - You may want to check if form2 is null in you click event. Answer updated.
Oded
A: 

I didn't checked if Visible property will work for Form, but you can try this.

public partial class MyForm: Form
    {
        public MyForm()
        {
            InitializeComponent();
        }

        Form2 f2 = null;
        private void Button1_Click (object sender, EventArgs e)
        (    
            if(f2 == null)
              f2 = new Form2();
            if(!f2.Visible)
              f2.Show ();
        )
    }
Marqus
thank you ever so much
Saska
+2  A: 

Similar to the existing answers, but with an extra event handler:

private Form f2 = null;
private void Button1_Click (object sender, EventArgs e)
{
    if (f2 == null)
    {
        f2 = new Form2();
        // Make sure we don't try to re-show a closed form
        f2.FormClosed += delegate { f2 = null; };
    }
    f2.Show ();
}
Jon Skeet
A: 

This code will open form. If previously form not oppened in application.

private void button1_Click(object sender, EventArgs e)
    {
        bool result = false;

        foreach (Form form in Application.OpenForms)
        {
            if (form.GetType() == typeof(Form2))
                result = true;
        }

        if (result == false)
            new Form2().Show();
    }
Mehmet Taskopru