Search code examples
c#winformswindows-10visual-studio-2017application-settings

WinForms Application settings are not assigning


Under Project > MyProject Properties > Settings I have an application setting named MyDouble with double type, the scope is User, the default value is 1.5.

I tried watching it, stepping through the entire application, and MessageBoxes to display the value. I've now commented out all uses of it excluding where I am trying to set a class (Form1) level variable. That looks like this:

    double myDouble = Properties.Settings.Default.MyDouble;

The value is always zero. If I MessageBox myDouble or the application setting the result is zero.

Some application settings are working. I called two message boxes in Form1_Shown event. One uses:

    Properties.Settings.Default.MyDouble.ToString() 

and the other uses:

    Properties.Settings.Default.MyInt.ToString()

The second one output the correct value.

This project is a WinForms application written in C#. Using Windows 10 and Visual Studio 2017. This project's form was copied over from a previous project, but I don't think that could affect it. The value in the previous project was the same. I typed these Application settings by hand. I've rechecked to ensure the spelling is correct. I deleted the setup project to no avail. Cleaned and rebuilt the solution... nada. I also checked the app.config file. I don't see anything wrong. Here it is:

    <userSettings>
        <MyProject.Properties.Settings>
            <setting name="MyDouble" serializeAs="String">
            <value>1.5</value>
            </setting>
        </MyProject.Properties.Settings>
    </userSettings>

Does anyone have any ideas why and/or how to fix this?


Solution

  • I think: something went wrong.

    In Solution Explorer, double-click the .settings file. The default name for this file is Settings.settings. In the Settings designer, find the Name (MyDouble) of your setting. Each row represents a single setting.

    See: Using Settings in C#.

    You have:

    <setting name="MyDouble" serializeAs="String">
    

    And you write:

    double myDouble = Properties.Settings.Default.MyDouble;
    

    Convert String to double...may be it wrong?

    See this page: Managing Application Settings (.NET) and this answer: What is the best way to store user settings for a .NET application?

    Try this code:

    Properties.Settings.Default.MyDouble = 1.5;
    Properties.Settings.Default.Save();
    

    and after it try this:

    var myDouble = Properties.Settings.Default.MyDouble;