简体   繁体   中英

Closing multiple forms C#

I'm currently working with C# windows forms. I got like 40 cs files, and when the applications works like : Pressing a button -> Opens new form upon the first one and pressing another button opens another form upon the one before.

Now, whenever I click multiple forms none of the others are closing itself when I'm pressing different buttons, they all stay on the background.

Now, if I use this.Close(); its working with 1, but i got like 40 cs files and it's hard to compile them all..

looking for any suggestion ? Thank you guys for any sort of help !

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

    private void button1_Click(object sender, EventArgs e)
    {
        NewCostumer mm = new NewCostumer();
        mm.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Remove_Customer mm = new Remove_Customer();
        mm.Show();
    }

    private void Costumers_Orders_Load(object sender, EventArgs e)
    {

    }

    private void button3_Click(object sender, EventArgs e)
    {
        Show_Edit_Customer mm = new Show_Edit_Customer();
        mm.Show();
    }

    private void button4_Click(object sender, EventArgs e)
    {
        Orders_report mm = new Orders_report();
        mm.Show();
    }
}

Assuming you only ever want one form open at a time, and that "Costumers" is the main form and can't be closed:

private void button1_Click(object sender, EventArgs e)
{
    ShowForm(new NewCostumer());
}

private void ShowForm(Form newForm)
{
    List<Form> forms = new List<Form>();
    foreach (Form frm in Application.OpenForms)
    {
        if (!(frm is Costumers))
        {
            forms.Add(frm);
        }
    }
    foreach (Form frm in forms)
    {
        frm.Close();
    }
    newForm.Show();
}

There are other ways you could do this as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM