简体   繁体   中英

How to pass values between forms in c# windows application?

I have two forms A and B. Form A is the default start up form of the application. I do some stuffs in Form A and i then i want to run my Form B parallel and then pass a parameter to a method in Form B from Form A.

How ?

Ian has given some example code, but I'd like to make a broader point:

UI classes are just classes.

How would you pass a value from one object to another object if they weren't part of the user interface? You'd have a reference from one to the other, and call a method or set a property. The same exact thing holds for user interface objects.

I mention this because it's something that comes up a lot. Whenever you ask yourself: "How do I do X with forms?" try asking yourself the same question but with plain old classes. Often the answer will be exactly the same.

Of course there are some differences for user interface classes - particularly with threading - but for an awful lot of cases, it really helps if you just think of them as normal classes.

FormA should construct/hold an instance to FormB. Obviously the method on FormB needs to be public, change the type of object used in CallMethodOnFormB to the correct type too.

public class FormA
{
   private FormB fB;

   public void CreateFormB()
   { 
      // This shows the form in parallel.
      this.fB = new FormB();
      this.fB.Show();
   }

   public void CallMethodOnFormB(object value)
   {
      this.fB.RunSomeFunction(value);
   }
}

Depending on your needs, another approach would be to introduce a global instance of a class (a singleton ), which can hold stuff that is to be shared between several forms/classes of your application.

For instance, if you have a form where the user can define his settings/preferences, you could store that data in a singleton. All other classes and forms of your application can then access/read these settings from the same singleton instance.

Here's a very basic example of a singleton:

public class MySettings
{
  // the one and only instace (the singleton):
  public static readonly MySettings Instance = new MySettings();
  private MySettings() {} // private constructor

  public int SomeNumber { get; set; }
  public string SomeString { get; set; }
}

Now you can access set/get the properties of MySetting from any other class/form in your application, eg:

in PreferencesForm.cs:

//read the user's input and store it in the settings
MySettings.Instance.SomeNumber = txtNumber.Value;

in SomeOtherForm.cs:

//read the user's setting and use it
int theNumber = MySettings.Instance.SomeNumber;
// do something with theNumber

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM