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

后端 未结 4 1456
渐次进展
渐次进展 2020-11-27 08:18

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 para

4条回答
  •  Happy的楠姐
    2020-11-27 08:36

    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, e.g:

    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
    

提交回复
热议问题