C# – How to close one FORM from another FORM in C# Winform Application

cformswinforms

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();
}

Best Answer

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!

Related Topic