ashraf ibrahim ashraf ibrahim - 1 year ago 64
C# Question

Close previous windows form when clicked other button

i try to close windows form in mdiparent when i click other button, the result is when i click other button, it still appear from the back of new window. so how can i handle this?

private void btn_ic_Click(object sender, EventArgs e)
{

pictureBox3.Visible = false;
SelectIC ss = new SelectIC();
ss.MdiParent = this;
ss.Show();
Detail aa = new Detail();
aa.MdiParent = this;
aa.Close();
btn_ic.Enabled = false;
btn_cat.Enabled = true;

}


private void btn_cat_Click(object sender, EventArgs e)
{
pictureBox3.Visible = false;
Detail aa = new Detail();
aa.MdiParent = this;
aa.Show();
SelectIC ss = new SelectIC();
ss.MdiParent = this;
ss.Close();
btn_cat.Enabled = false;
btn_ic.Enabled = true;
}

Answer Source

You're making new instance of form and then closing it. That way you're not closing existing window but creating new (invisible) one and closing it. You should find existing window in collection of MdiChildren and then close it. Something like this:

private void btn_ic_Click(object sender, EventArgs e)
{

    pictureBox3.Visible = false;
    SelectIC ss = new SelectIC();
    ss.MdiParent = this;
    ss.Show();

    var detailForm = this.MdiChildren.FirstOrDefault(f => f.GetType() == typeof(Detail));
    detailForm?.Close();

    btn_ic.Enabled = false;
    btn_cat.Enabled = true;

}

private void btn_cat_Click(object sender, EventArgs e)
{
    pictureBox3.Visible = false;
    Detail aa = new Detail();
    aa.MdiParent = this;
    aa.Show();

    var selectForm = this.MdiChildren.FirstOrDefault(f => f.GetType() == typeof(SelectIC));
    selectForm?.Close();

    btn_cat.Enabled = false;
    btn_ic.Enabled = true;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download