Question

I use the VSTO built-in settings file in order to save Windows- application settings.

I have a checkBox on my WinForm, whereas at form load I read its state (checked or unchecked) from the appropriate property in the settings file.

This works fine as long as I do not exit the application.
However, when I quit and then execute the application again- the settings are not saved from last execution and the checkBox state is not as the last preference.

I use "user" scope to save the settings.

On form load, extract the checkBox state from Settings.

private void MyFormLoad(object sender, EventArgs e)
    {  
     //Find the appropriate property in the Settings file
      System.Configuration.SettingsProperty property;  
      property = P_Settings.Settings.Default.Properties[checkBox.Name]; 

      if (property != null) 
          checkBox.Checked = Convert.ToBoolean(property.DefaultValue);
    }  

On form close, Synchronize settings file with form status.

private void ButtonApplyClick(object sender, EventArgs e)
    {    
    System.Configuration.SettingsProperty property;  
    property = P_Settings.Settings.Default.Properties[checkBox.Name];   

    property.DefaultValue = checkBox.Checked.ToString();  
    P_Settings.Settings.Default.Save();
   }
Was it helpful?

Solution

I don't think the DefaultValue is where you should store the value for a settings property. That looks more like a part of the property definition (which should stay constant across application runs and thus be hard-coded) rather than like something that will be saved along with the settings.

Instead, try directly using the indexer of the settings object:

Loading:

object propValue = P_Settings.Settings.Default[checkBox.Name];
if (propValue != null) {
    checkBox.Checked = Convert.ToBoolean(propValue);
}

Saving:

P_Settings.Settings.Default[checkBox.Name] = checkBox.Checked.ToString();
P_Settings.Settings.Default.Save();

EDIT: Originally, you were storing the checkbox state in the DefaultValue property of the settings property. The DefaultValue is meant to provide a default value that will be returned if no settings value was found in the stored settings. It is not a value that will be stored with the settings, as it is not supposed to be user-defined, or changed during the application's run.

Therefore, what you tried before resulted in the observed behavior: You could assign a value to DefaultValue, which would stay for as long as the application was active, but that value was not stored upon P_Settings.Settings.Default.Save() or restored upon application startup, so upon the next launch of your application, DefaultValue would have its default value (probably null) again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top