0

I'm working on C# winform application, in that I want to close one form from the another form i.e. I have 2 forms Form1 and Form2 and I want to close Form2 from Form1 for that I have written following code on button click event of Form1, but I'm getting the following exception-

"Object reference not set to an instance of an object."

private void button_click(object sender, eventArgs e)
{
     Form2.ActiveForm.Disposed+= new EventHandler(closeForm2) // Getting Exception to ***closeForm2***
}

private void closeForm2(object sender, eventArgs e)
{
      Form2.ActiveForm.Dispose();
}
user513951
  • 12,445
  • 7
  • 65
  • 82
Namo
  • 157
  • 1
  • 6
  • 17
  • 1
    [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Oct 09 '14 at 10:12

4 Answers4

4

For future readers!

You can use the following code to close one FORM from another FORM in C# Winform Application.

FrmToBeClosed obj = (FrmToBeClosed)Application.OpenForms["FrmToBeClosed"];
obj.Close();

Those 2 lines of code are self-explanatory!

That's it!

Abdisamad Khalif
  • 765
  • 2
  • 7
  • 19
0

ActiveForm returns "Currently active form from this application" = Form you clicked... How you start your Form2? I think you should define it like

Form2 DetailsForm = null;
public void prepareForm2() //bind this to action to open new form
{
    if (DetailsForm == null)
    {
        DetailsForm = new Form2(this);
    }
}

Than you can just call close()/Dispose/Hide by calling

private void closeForm2(object sender, eventArgs e)
{
   DetailsForm.Close();
   // or DetailsForm.Hide();
   // or DetailsForm.Dispose();
}
Laky
  • 373
  • 4
  • 17
  • I have taken a MDIParent Form and calling Form1 and Form2 on ToolStripMenuItem_Click event as shown below-- private void form1ToolStripMenuItem_Click(object sender, EventArgs e) { Form1 f = new Form1(); f.MdiParent = this; f.Show(); } private void form2ToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f = new Form2(); f.MdiParent = this; f.Show(); } – Namo Oct 09 '14 at 10:38
0

See MSDN -> Form.ActiveForm Property

If your application is a multiple-document interface (MDI) application, use the ActiveMdiChild property to obtain the currently active MDI child form.

I think you need a void in your MDI-Form like

public void closeChild(Type FormType)
{
  foreach(Form form in this.MdiChildren)
  {
    if(typeof(form) == FormType)
    {
       /* what ever you wanna do */
    }
  }
}

Hope I could help :)

DJmRek
  • 378
  • 6
  • 13
0
 CloseProgramForm closepf = new CloseProgramForm();
            closepf.ShowDialog();
            if (closeoption == 1)
                e.Cancel = false;
            else
                e.Cancel = true;