ispiro
ispiro

Reputation: 27633

Application.Settings Save() doesn't save the instance's value (in this case)

I'm trying to implement a "Reset Settings" button on a Settings Form. But I don't want it committed until an OK from the user.

So I create a copy of the settings before resetting them, and if the user clicks Cancel - I save those ("old") settings. Trouble is - it doesn't work.

Here is the code:

Settings s1 = Settings.Default;
s1.Setting1 = "A";
s1.Save();
Settings s2 = Clone();//A method that clones the settings
s2.Setting1 = "B";
s2.Reset();
s1.Save();//Why doesn't this line work?
s1.Reload();//Without this line - the next line shows "A" . With this line, the next shows - "ABC" (-the origianl). Why?
Text = s1.Setting1;

(Extra: Should I be changing the settings upon every change by the user in a copy of the settings, and committing those after an OK, or should I ignore the changes until a user clicks OK - and then go over all of the Controls and assign each Control's value to the correct property... Or perhaps some other way?)

Upvotes: 1

Views: 281

Answers (1)

dotNET
dotNET

Reputation: 35380

If this is WinForms or WPF, use Application Settings Binding mechanism that ships with VS. That way you don't have to explicitly open/save your settings. Instead you bind your front-end controls directly to a particular setting and it will automatically read/write settings for you. If user presses Cancel in your dialog, you can simply call Settings.Reload() to get things rolled back.

Suppose you have a setting called UserName (string) that you want to save so that user doesn't have to type it every time. Simply click on your TextBox in the designer and go to Properties window. At the very top you'll see (ApplicationSettings) property. Expand it and you should see Text property. Click it and then from the dropdown choose New (or choose your property from the list if you have already defined it). Type a property name and a default value and click OK. It will create a property for you and bind the TextBox with this property. And you're done!

Upvotes: 1

Related Questions