Home > Back-end >  How do you stop multiple forms from opening when you click a button more than once
How do you stop multiple forms from opening when you click a button more than once

Time:09-21

private void Button_Click_1(object sender, EventArgs e)
{
    Form2.form = new Form2();
    form.Show();
}

When you click the button twice, 2 forms pop up, how do I make it so when you click the button twice it gets rid of the form already open and opens up the form alone.

Example of what I want:

  • Click the button once, makes Form2 open

  • Click the button twice, makes the original Form2 close, and open another Form2 alone.

What actually happens:

  • Click the button once, makes Form2 open

  • Click the button twice, the original Form2 is still open and it opens another Form2

CodePudding user response:

You'll just need to loop through each of the open forms and check the name of the form to see if it is the same. Try the following:

foreach (Form frm in Application.OpenForms)
{
    if (frm.Name == "form2") //Whatever the actual name of your form is
    {
        frm.Close();
    }
}

Form2 form2 = new Form2();
form2.Show();

CodePudding user response:

You can build a simple method that verifies whether an instance of a Form of a Type you supply exists: if it does, closes the current instance and generates a new one of the same Type:

private void OpenNew<T>() where T : Form, new()
{
    var instance = Application.OpenForms.OfType<T>().FirstOrDefault();
    if (instance != null) instance.Close();
    new T().Show();
}

Assuming that you generate an instance of this Type only using a specific Button.

If more than one instance of that Type can exist, for some reason, loop the collection returned by Application.OpenForms.OfType<T>() ( .ToArray() to avoid... well, try it without it ):

private void OpenNew<T>() where T : Form, new()
{
    foreach (var instance in Application.OpenForms.OfType<T>().ToArray()) {
        instance.Close();
    }
    new T().Show();
}

=> you can loop the collection also as:

Application.OpenForms.OfType<T>().ToList().ForEach(f => f.Close());

You can call either of these methods (use the one you prefer in your context: you may need to do something else before showing a new, always single, instance or a new one of the many) as, e.g., :

OpenNew<Form2>();
  • Related