首页 > 解决方案 > WinForms 应用程序设置更改似乎没有持续

问题描述

在我的 C# WinForm 中,我有一个设置窗口,允许用户更改数据库连接设置。在设计时,我设置了可以成功连接到数据库的初始设置。

我通过以下两种方式之一访问这些设置:

在解决方案资源管理器中:

在此处输入图像描述

或者在项目的应用程序设置中:

在此处输入图像描述

但是,我注意到,如果我更改 Settings.Settings 文件中的任何值,表单仍会加载我最初设置的值。

需要明确的是:其中一项设置是服务器,它是一个 IP 地址。我最初将其设置为 256.256.256.256(当然是虚拟 IP)。该程序运行良好并连接到数据库正常。

然后我把Settings.Settings文件中的IP地址改成了255.255.255.2,就连不上了。但是当我运行表单时,它仍然使用最初设置的 IP 地址进行连接。

在我的表单加载事件中,我有这个:

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();
    }
}

这是我的 Db.cs 类中的 TestDbConnectionSettings 方法:

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;
    }

}

所以,它应该从设置文件中读取(至少这是我的意图),但它似乎不再是 - 至少。凭直觉,我将代码放在 Db.cs 中,将值设置connString为 TestDbConnectionSettings 方法本身,但这并没有改变任何东西。

标签: c#winformsapplication-settings

解决方案


推荐阅读