Click here to Skip to main content
11,927,711 members (33,670 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# Forms
So I have a main form called 'form1' from which I can click a button to show another form called 'form2'. How can I run some code in 'form1' when the event of 'form2' closing occurs?
Posted 8-Nov-12 17:44pm
What's so special about this case? Why this is a problem? Do you know how handle events or override methods? Did you see MSDN help on forms? What did you try?
FourCrate 9-Nov-12 18:59pm
Not really, I've been searching a lot but couldn't find anything. I guess I'm not searching the right thing that will solve the problem. I was too stumped to even try it, but the below example helps and I'll use that to find out more.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Take a look:
form2.FormClosed += (sender, eventArgs) => {
    // some code
form2.FormClosing += (sender, eventArgs) => {
    Form senderForm = (Form)sender; // will always cast to this type, no need to check up, see below
    // some code
    // but you can also prevent closing of the form based of some condition:
    if (shouldNotCloseIt /* whatever */ && eventArgs.CloseReason == UserClosing) {
        eventArgs.Cancel = true;
        senderForm.Hide(); // typical use of it; actually senderForm == form2, see above
    } // if
    // some more code

Please see:[^],[^],[^],[^].

Rahul Rajat Singh 9-Nov-12 1:19am
oh I was about to write the same, i even wrote all the code but you beat me to it :(

nevertheless, +5.
Thank you, Rahul.
FourCrate 9-Nov-12 18:57pm
Many thanks, it worked
Great. You are welcome.
Good luck, call again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web03 | 2.8.151126.1 | Last Updated 9 Nov 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100