c# - 通知模态表单的父级它需要采取一些行动

标签 c# .net winforms events modal-dialog

我有一个父表单打开一个模态表单,它基本上允许用户更改应用程序的数据库设置。

当用户单击模态(子)表单上的保存按钮时,它会使用新设置保存设置对象,但我需要让主表单检查数据库设置是否正确。

我目前通过一个尝试简单地连接到数据库的函数来执行此操作,如果成功则返回 true,如果失败则返回 false。我在应用程序构造函数中执行该函数,因此无论何时关闭并重新启动应用程序,它都能正常运行。

保存设置后,我在模态表单中尝试了以下操作,但对象 myManager 出现 NullReference 异常。

这是获取新设置并保存它们然后尝试调用父窗体 CheckDatabaseIsSetup() 公共(public)函数来测试数据库连接的函数。

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

最佳答案

您应该改为使用模式窗体中的 Owner 属性而不是 ParentForm 属性,如下所示:

BushBreaksLodgeManagerMain myManager = (BushBreaksLodgeManagerMain)this.Owner;

Owner 属性定义了拥有(模态)表单和父(所有者)表单之间的实际关系。

关于c# - 通知模态表单的父级它需要采取一些行动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135051/

相关文章:

c# - JSON.NET 到 C# 对象

c# - 代码、配置或 Visual Studio 中是否有任何设置不会在已发布的代码中生成 .PDB 文件?

.net - 在 TextBox 中以 d/mm 格式输入日期

.net - 如何在多项目、单一解决方案环境(VS2012)中调用Forms?

c# - 带有 C# 的 ASP.net 在回发时保留列表

C# Jagged arrays for loop 实现问题

c# - 'SAPI 没有实现拼音选择' 异常

C# UserControl.VerticalScroll.Value 未设置

c# - 表单加载时出现 datagridview 错误 : index was out of range exception

c# - 我的 .net core 发布的可执行文件提供了与运行代码时不同的目录路径