How to Pass Variables between Windows Forms Windows without ShowDialog() When you are programming a Windows Forms application, you will invariably need to get variables from a second form window, such as an options form or popup search prompt.
Most of the guides out there will tell you that you have to open the second form with ShowDialog(), which blocks the user from doing anything else until they’ve closed the second form window. This won’t work very well for a find/replace dialog, for instance. It also won’t work very well for custom drawn popup forms.
The quick way to pass variables between the forms is using Delegates. You can set an eventhandler for the Closing event of the second form, and handle the event in the first form. This allows you to capture variables before the second form window has closed. Pass Variables between Windows Forms
For this exercise, we’re going to assume that we have two forms:
We’re going to further assume that we’ve clicked some sort of button that opens the OptionsForm with a Show() method call. Now let’s take a look at the magic:
OptionsForm theform = new OptionsForm(); theform.Closing += new CancelEventHandler(theform_Closing); theform.Show();
Am a Kenyan Based Politician, Senior blogger, Digital Communications expert, YouTuber, Pan Africanist, columnist, Human Rights Activist, informer & businessman. Contact me on +254791890826 or Email Me on firstname.lastname@example.org