day0ops
day0ops

Reputation: 7482

C# persisting data between two winforms

I have not been able to find a solution to my problem yet. What I have is two winforms, Main and a Configuration Settings form. The configuration settings form can be accessed from the menu of the Main form.

What I want to do is have a single instance of the Configuration settings form so when the user enters the information in the form it gets passed back to the main form and closes. But if the user decides to go back to the configuration settings form the previous entered information appears.

The configuration settings basically has two input boxes and an OK button.

How can I implement this ?

Upvotes: 0

Views: 394

Answers (2)

Neowizard
Neowizard

Reputation: 3017

You've got many options. For instance:

  • You can store the latest serialized configuration data on the hard drive\DB (using some temp file).
  • You can pass the last defined config as a constructor parameter (and return it to the calling form upon close).
  • You can cancel the form's close event and hide it instead, and when you try to reopen it, you make it visible instead.
  • you can use a singletone (like @Kamil said)

When it comes to configuration windows, I like to either store their data to the drive\DB or to pass their initial state to the constructor.

Upvotes: 0

Kamil Lach
Kamil Lach

Reputation: 4629

For configuration purpose you can use singleton pattern to store configuration data.

class ConfigurationStorage{
      private static ConfigurationStorage _instance;

      // settng example - ConnectionString    
      public string ConnectionString {get;set;}

      public static ConfigurationStorage GetInstance(){
          return _instance ?? (_instance =  new ConfigurationStorage());
      }
}

In configuration form you can do:

ConfigurationStorage.GetInstance().ConnectionString  = "buu";

to store data, and same thing in Main form to retrive it (because is the same object)

Also you can use Form Parent property to set settings explicity to MainForm.

Upvotes: 2

Related Questions