How to pass a value selected on an initial form to the main form?

I want to do something like the answer here:

How can I close a login form and show the main form without my application closing?

...but I want to pass a value selected on the initial form to the next (main) form. If I call an overridden constructor on the main form, where do I store the value in the meantime (between the initial form being dismissed and the main form being called)?

OTOH, if, instead of using the program.cs file to do this, I create the "initial form" inside the main form's Load() event (is there a better place), I could do something like this, but admittedly it seems rather kludgy:

0) Set the main form's size to 0,0 to hide it 1) Show the "initial" form/modal dialog, and store the value the user selects (in a button click event) in a form-global variable 2) Once the initial form/modal dialog closes, set the main form's size back to what it should be (unless modal result <> OK, in which case I close the main form and the app)

I know there's a better way to do this...

Upvotes: 0

Views: 359

Answers (2)

VPK
VPK

Reputation: 31

Try using ApplicationContext (System.Windows.Forms.ApplicationContext). You can show multiple forms as shown in the example in the following MSDN thread. And regarding data,you can have a common data object which is created once and the forms are instantiated with the data object passed to them before showing them.

http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext%28v=vs.100%29.aspx

Upvotes: 1

Bob Horn
Bob Horn

Reputation: 34335

You don't have to pass a value to the main form. Just like your link explains, open your main form first. Then your main form can open the other form. This other form can place the information in a public property that the main form can access. Since the main form controls the lifetime of this other form, the main form gets the information held in the other form's public property, then closes the other form.

string myVariable;

using (OtherForm otherForm = new OtherForm())
{
  otherForm.ShowDialog();
  myVariable = otherForm.OtherVariable;
}

Upvotes: 2

Related Questions