Subscribe to How-To Geek

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.

For this exercise, we’re going to assume that we have two forms:

MainForm

OptionsForm

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:

……. snip…….

OptionsForm theform = new OptionsForm();
theform.Closing += new CancelEventHandler(theform_Closing);
theform.Show();

}

private void theform_Closing(object sender, CancelEventArgs e)
{

   OptionsForm theform = (OptionsForm)sender;

   // Grab the variable from the options form. The options form should set this variable before it closes, and the variable should be marked as public.
   string localvar = theform.thestringvariable;

}

 

That’s all there is to it.

| More
This article was originally written on 09/20/06 Tagged with: Programming

Daily Email Updates

You can get our how-to articles in your inbox each day for free. Just enter your name and email below:


Name:
Email:

Comments (2)

  1. cypher

    I guess this works better :
    theform.FormClosing += new FormClosingEventHandler(theform_Closing);

    Thanks it helped me a lot to figure it out anyway.

  2. Rama krishna

    it worked for me as well in great deal

    A big thanks for the person who has given the hint


Leave a Comment




Leave your friendly comment here.

If you have a computer help question, click here to leave it on the forums instead.

Note: Your comment may not show up immediately on the site.

Our Friends
Getting Started


About How-To Geek
What Is That Process?
svchost.exe
jusched.exe
dwm.exe
ctfmon.exe
wmpnetwk.exe
wmpnscfg.exe
rundll32.exe
wfcrun32.exe
Ipoint.exe
Itype.exe
Wfica32.exe
Mobsync.exe
conhost.exe
Dpupdchk.exe Adobe_Updater.exe

Copyright © 2006-2009 HowToGeek.com. All Rights Reserved.