Click here to Skip to main content
Rate this: bad
good
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
Comments
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?
--SA
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
good
Please Sign up or sign in to vote.

Solution 1

Take a look:
form2.FormClosed += (sender, eventArgs) => {
    // some code
};
or
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:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.formclosingeventargs.closereason.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.closereason.aspx[^].
 
—SA
  Permalink  
v3
Comments
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.
--SA
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.
--SA

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

  Print Answers RSS
0 OriginalGriff 304
1 Maciej Los 285
2 Sergey Alexandrovich Kryukov 255
3 Shweta N Mishra 216
4 PIEBALDconsult 174
0 OriginalGriff 7,660
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,760


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 9 Nov 2012
Copyright © CodeProject, 1999-2014
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