Ok, so a Windows Forms class, WindowSettings, and the form has a "Cancel"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the user if he is sure he wants to perform the action. The dialog has 2 buttons, a "Yes"-button and a "No"-button. If the user clicks the "Yes"-button, I want both DialogSettingsCancel and WindowSettings to be closed.
My button_Click event handler in DialogSettingsCancel:
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
WindowSettings settings = new WindowSettings();
this.Close();
settings.Close();
}
When I run my application, and go to the settings form, and click the "Cancel"-button, and then click the "Yes"-button, only DialogSettingsCancel closes without closing WindowSettings.
Why won't it work?
I've also tried changing
this.Close();
settings.Close();
to
settings.Close();
this.Close();
But still the same result.
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
2.We can also hide form without closing it
There are different methods to open or close winform. Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed. Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Some methods to Open/Start a form
All of them act differently , Explore them !
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
You need the actual instance of the
WindowSettings
that's open, not a new one.Currently, you are creating a new instance of
WindowSettings
and callingClose
on that. That doesn't do anything because that new instance never has been shown.Instead, when showing
DialogSettingsCancel
set the current instance ofWindowSettings
as the parent.Something like this:
In
WindowSettings
:In
DialogSettingsCancel
:This approach takes into account, that a
DialogSettingsCancel
could potentially be opened without aWindowsSettings
as parent.If the two are always connected, you should instead use a constructor parameter:
In
WindowSettings
:In
DialogSettingsCancel
:Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:
You can also close the application:
It will end the processes.