问题
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