Domanda

I'm putting together a simple UI that interacts with a SQL database. My problem is a UI problem, ever time a menustrip item is selected, it opens a new active window. How do I set this up to close the previous active window? I've tried using Form.Close();, but that just closes everything.

private void addCampusToolStripMenuItem_Click(object sender, EventArgs e)
{
    if_add_campus go = new if_add_campus();
    go.Show();
}

private void addDepartmentToolStripMenuItem_Click(object sender, EventArgs e)
{
    if_add_dept go = new if_add_dept();
    go.Show();
}

private void addEmployeToolStripMenuItem_Click(object sender, EventArgs e)
{
    if_add_employee go = new if_add_employee();
    go.Show();
}
È stato utile?

Soluzione

Just keep track of the last form you created in a variable:

    private Form lastForm;

    private void showForm(Form frm) {
        frm.FormClosed += (sender, ea) => {
            if (object.ReferenceEquals(lastForm, sender)) lastForm = null;
        };
        frm.Show();
        if (lastForm != null) lastForm.Close();
        lastForm = frm;
    }

And use showForm() to display your forms:

private void addCampusToolStripMenuItem_Click(object sender, EventArgs e)
{
    showForm(new if_add_campus());
}

Not tested, should be close.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top