Happy
Happy

Reputation: 1145

How to close current form Winform C#

I've got an MDIParent and I've opened a child window. I need to close the current parent if button is clicked. So I've tried the code below

private void button_log_Click(object sender, EventArgs e)
    {
        MDIParent_Main obj = new MDIParent_Main(textBox_username.Text);
            obj.Show();
            this.Close();
     }

The problem is it's closing both MDIParent_Main and child form. Where is my error?

Upvotes: 2

Views: 13287

Answers (2)

Liath
Liath

Reputation: 10191

The problem you have is that your MDIParent form is the main application form. When you close it the application is ending and taking the child windows with it see this question for more details.

Once of the wildly accepted solutions is to hide the parent form until the child is also closed. Once the child is closed you can close the parent.

// code taken from referenced question
private void btnOpenForm_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
    frm2.Show();
    this.Hide();
}


private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
    this.Close();
}

Upvotes: 3

abrfra
abrfra

Reputation: 654

you can not do that in that way. you must first open the mdipather, than show() the login form, than close the login form when autenticaded

Upvotes: 0

Related Questions