Click here to Skip to main content
11,806,818 members (57,887 online)
Rate this: bad
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 16:44pm
Sergey Alexandrovich Kryukov at 9-Nov-12 0:58am
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 at 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 at 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.
Sergey Alexandrovich Kryukov at 9-Nov-12 1:23am
Thank you, Rahul.
FourCrate at 9-Nov-12 18:57pm
Many thanks, it worked
Sergey Alexandrovich Kryukov at 9-Nov-12 19:12pm
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
0 ppolymorphe 245
1 OriginalGriff 150
2 George Jonsson 145
3 CPallini 100
4 Abhinav S 80
0 OriginalGriff 3,380
1 Maciej Los 1,990
2 CPallini 1,915
3 KrunalRohit 1,907
4 ppolymorphe 1,317

Advertise | Privacy | Mobile
Web04 | 2.8.151002.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