2

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?

Liath
  • 9,913
  • 9
  • 51
  • 81
Happy
  • 1,105
  • 5
  • 17
  • 25
  • if `this` is also an MdiParent, then that is your answer. The form you are opening would belong to `this`, so closing `this` closes all. – DonBoitnott Jan 23 '14 at 14:31
  • The problem you have is that your application is ending when you're closing the parent window. Take a look at this http://stackoverflow.com/questions/40962/how-do-i-close-a-parent-form-from-child-form-in-windows-forms-2-0 – Liath Jan 23 '14 at 14:31
  • @DonBoitnott, good spot I assumed this.Close() was intentionally closing the parent – Liath Jan 23 '14 at 14:31
  • @Liath thanks for your link. i tried to close parent form... – Happy Jan 23 '14 at 14:36
  • @Happy just to clarify, you're trying to close the parent form and leave the child form open? – Liath Jan 23 '14 at 14:37
  • I've updated as much as possible – Liath Jan 23 '14 at 14:48

2 Answers2

3

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();
}
Community
  • 1
  • 1
Liath
  • 9,913
  • 9
  • 51
  • 81
0

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

abrfra
  • 634
  • 2
  • 6
  • 24