-2

I have created 2 forms in Winforms. I have button in Form1 and some text in form2. When the button in the form is clicked, I made to show the form2 by click event. When i close the form2 the form1 also getting closed.

But i want the form1 not to be closed.

Form1 Code :

    public Form1()
    {
        InitializeComponent();
        button1.Click += Button1_Click;
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        var form = new Form2();
        form.Show();
    }

Form2 :

Simply displaying the details like name and city details.

I just created simple sample, Since am in starting stage.

Please share your ideas and thoughts.

  • Please consider posting a [MCVE]. – Reza Aghaei Dec 19 '18 at 12:37
  • 2
    It's not the default behavior. By trying to reproduce the problem in a clean project, having 2 clean forms, you will be able to find the problem. If you couldn't find the problem yourself, then you can share that [MCVE] here. – Reza Aghaei Dec 19 '18 at 12:39

1 Answers1

0

Form1 should remember which Form2 it created. When Form2 is closed it should notify Form1, so Form1 can nullify its reference to Form2

private Form2 form2 = null;

void ShowForm2(...)
{
    if (this.form2 != null) return; // form2 already shown

    this.form2 = new Form2();
    // make sure you get notified if form 2 is closed:
    this.form2.FormClosed += onFormClosed;
}

void OnFormClosed(object sender, EventArgs e)
{
     if (object.ReferenceEquals(sender, this.form2)
     {
          // form2 notifies that it has been closed
          // form2 will Dispose itself
          this.form2 = null;
     }
}

Neat closure of Form1 and Form2

Note: if Form1 is Closing, it would to nice to ask Form2 whether Closing is allowed (maybe if needs to ask the operator?). If Form2 doesn't want to Close, cancel Closing Form1.

If closing is allowed, remember that you were closing Form1 and close Form2. When Form2 notifies Form1 that it is closed, check whether you were closing, and if so, re-start the closing procedure, this time there won't be a Form2, and closing can continue normally.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • When you show a form using `Show`, by closing it, it will automatically dispose. Take a look at this post: [Do I need to Dispose a Form after the Form got Closed?](https://stackoverflow.com/a/39501121/3110834) – Reza Aghaei Dec 19 '18 at 14:34