c# - 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 方法本身,但这并没有改变任何东西。
解决方案
推荐阅读
- arrays - 有人可以澄清这是要我做什么吗?
- spring - Spring @ConfiurationProperties 扩展毛的问题
- django - Docker 拉取 Django 镜像并运行容器
- javascript - 如何在 javascript 命令 (.innerHTML) 中编辑变量名?
- javascript - 即使有硬编码延迟,在每个 mouseEvent 之后执行 setTimeout 的时间延迟也会增加一倍甚至三倍;
- angular - Angular 8 - 注入类以指示表格排序方向
- apache-kafka - 具有一对多连接的 Kafka Sink 连接器
- c# - 在改变场景时继续相同的音频 - Unity
- angular - POST 请求的 .NET Core CORS 问题
- jenkins - 如何从脚本 [SonarQube 6.5] 动态地将质量门分配给项目?