2

I wrote this to quickly test

Why arent my settings being saved? The first time i run this i have 3(old)/3(current) elements. The second time i get 3(old)/5(current), third time 5(old)/5(current).

When i close the app the settings completely disappear. Its 3 again when i run it. I made no changes to the app. Why arent my settings being saved

    private void button2_Click(object sender, EventArgs e)
    {
        MyApp.Properties.Settings.Default.Reload();
        var saveDataold = MyApp.Properties.Settings.Default.Context;
        var saveData = MyApp.Properties.Settings.Default.Context;
        saveData["user"] = textBox1.Text;
        saveData["pass"] = textBox2.Text;
        MyApp.Properties.Settings.Default.Save();
    }

1 Answers1

4

You should be using the exposed properties instead of putting your data in the context:

var saveData = MyApp.Properties.Settings.Default;
saveData.user = textBox1.Text;
saveData.pass = textBox2.Text;

The context

provides contextual information that the provider can use when persisting settings

and is in my understanding not used to store the actual setting values.

Update: if you don't want to use the Settings editor in Visual Studio to generate the strong-typed properties you can code it yourself. The code generated by VS have a structure like this:

    [UserScopedSetting]
    [DebuggerNonUserCode]
    [DefaultSettingValue("")]
    public string SettingName
    {
        get { return ((string)(this["SettingName"])); }
        set { this["SettingName"] = value; }
    }

You can easily add more properties by editing the Settings.Designer.cs file.

If you don't want to use the strong-typed properties you can use the this[name] indexer directly. Then your example will look like this:

    var saveData = MyApp.Properties.Settings.Default;
    saveData["user"] = textBox1.Text;
    saveData["pass"] = textBox2.Text;
Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • thats... not great :(. So do i need to create the properties in the IDE or can i do it in code somehow? –  Jan 25 '10 at 10:32
  • To bad i cant just donate points to you. Great answer. I looked into it, i was hoping i could have a NameValueCollection but it doesnt look possible. However a string version is available. I guess objects/boxing isnt available. If i want to generate fields (ATM i just like writing fields inline and in code over IDEs) i could just use the string collection which isnt bad. –  Jan 25 '10 at 11:28
  • You _could_ if you added a bounty on the question before accepting, lol! Anyways, glad to be of assistance. – Peter Lillevold Jan 25 '10 at 11:39