【发布时间】:2011-11-15 10:41:42
【问题描述】:
我有一个父表单打开一个模式表单,它基本上允许用户更改应用程序的数据库设置。
当用户单击模态(子)窗体上的保存按钮时,它会使用新设置保存设置对象,但我需要让主窗体检查数据库设置是否正确。
我目前通过一个尝试简单地连接到数据库的函数来执行此操作,如果成功则返回 true,如果失败则返回 false。我在应用程序构造函数中执行该函数,因此每当应用程序关闭和重新启动时它都能正常运行。
保存设置后,我在模态表单中尝试了以下操作,但对象 myManager 出现 NullReference 异常。
这是获取新设置并保存它们然后尝试调用父表单 CheckDatabaseIsSetup() 公共函数来测试数据库连接的函数。
/// <summary>
/// Save the settings and then hide the Settings window
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Save_Click(object sender, EventArgs e)
{
// TRUE: User indicates that we are to connect using a trusted connection
// FALSE: User wants to use Integrated security to connect.
if (rb_UseTrustedConnection.Checked)
{
AppSettings.DatabaseName = tb_Trusted_DbName.Text;
AppSettings.Server = tb_Trusted_Server.Text;
AppSettings.UseIntergratedSecurity = false;
}
else
{
AppSettings.DatabaseName = tb_Secure_DbName.Text;
AppSettings.Server = tb_Secure_Server.Text;
AppSettings.Username = tb_Secure_Username.Text;
AppSettings.Password = tb_Secure_Password.Text;
AppSettings.UseIntergratedSecurity = true;
}
try
{
AppSettings.SaveSettings();
BushBreaksLodgeManagerMain myManager = (BushBreaksLodgeManagerMain)this.ParentForm;
myManager.CheckDatabaseIsSetup();
}
catch (Exception ex)
{
log.LogAppendWithException(ex);
}
this.Hide();
}
【问题讨论】:
-
为什么不将 CheckDatabaseIsSetup() 中的代码放入某种设置管理器类中,然后您可以从任何您想要的地方调用它。表单中的代码应该与 UI 相关。
-
Ben,抱歉,我应该提到主窗体的函数 CheckDatabaseIsSetup() 调用测试连接的 databaseutilities 类的 TestDatabaseConnection。所以它在一个单独的对象中。我在主函数中调用的原因是如果连接失败,允许主窗体打开数据库设置窗体。
标签: c# .net winforms events modal-dialog