WinForms Application Settings changes don't appear to be persisting

♀尐吖头ヾ 提交于 2020-05-17 06:34:32

问题


In my C# WinForm I have a settings window that allows the user to change database connection settings. At design time I set the initial settings that would connect to a database successfully.

I'm accessing those settings in either of two ways:

Either in the Solution Explorer:

Or in the Project's Application Settings:

However, I noticed that if I change any of the values in the Settings.Settings file, the form still loads with the values that I initially set each to.

To be clear: one of the settings is the server, which is an IP address. I initially set it to 256.256.256.256 (dummy IP, of course). The program ran fine and connected to the db fine.

Then I changed the IP address in the Settings.Settings file to 255.255.255.2, which won't connect. But when I run the form it still connected using the originally set IP address.

In my form load event I have this:

db connectionTest = new db();
if (!connectionTest.TestDbConnectionSettings())
{
    DialogResult diagResult = MessageBox.Show("Unable to connect to the database using the entered settings." +
        "\n" +
        "\n" +
        "Click OK to open the Connection Settings window.", "Database Connection Test Failed", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
    if(diagResult == DialogResult.OK)
    {
        frmDbConnectionInfo frm = new frmDbConnectionInfo();
        frm.Show();
    }
}

And here's the TestDbConnectionSettings method in my Db.cs class:

private readonly string connString = string.Format("Server = {0}; Port = {1}; User Id = {2}; Password = {3}; Database = {4};", 
        Properties.Settings.Default.serverSetting,
        Properties.Settings.Default.portSetting,
        Properties.Settings.Default.userIdSetting,
        Properties.Settings.Default.passwordSetting,
        Properties.Settings.Default.databaseSetting);

public bool TestDbConnectionSettings()
{
    try
    {
        Cursor.Current = Cursors.WaitCursor;
        using (NpgsqlConnection conn = new NpgsqlConnection(connString))
        {
            conn.Open();
            Cursor.Current = Cursors.Default;
            return true;
        }
    }
    catch
    {
        Cursor.Current = Cursors.Default;
        return false;
    }

}

So, it should be reading from the settings file (at least that's my intention), but it doesn't appear to be - anymore, at least. On a hunch I placed the code in Db.cs that sets the values for connString into the TestDbConnectionSettings method itself, but that didn't change anything.

来源:https://stackoverflow.com/questions/61018443/winforms-application-settings-changes-dont-appear-to-be-persisting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!