【问题标题】:OpenDatabaseForm that behaves like OpenFileDialog行为类似于 OpenFileDialog 的 OpenDatabaseForm
【发布时间】:2019-07-15 21:08:41
【问题描述】:

我正在为我的程序使用嵌入式数据库 (SQLite),因此当用户想要使用现有数据库条目时,他们可以使用简单的 winforms UI 查看数据库中的文件,选择一个并继续程序。

我已经制作了 UI,但需要表单来展示类似于 OpenFileDialog w.r.t 的行为。以下:

if(openFileDialog.ShowDialog() == DialogResult.OK)
      file = openFileDialog.FileName;

所以它应该如下所示:

OpenDatabaseDialog odd = new OpenDatabaseDialog();
odd.Show();
if(odd.IsOK)
      file = odd.FileName;

我已经尝试在我的 OpenDatabaseDialog 中公开一些属性,IsOk(如果表单成功从用户那里获得文件名,则为 true)和 FileName(应该包含实际文件名字符串的字符串)。

问题是,程序并没有等待 OpenDatabaseDialog 实际执行,它只是跳过了选择结构,这当然会失败,因为用户没有时间输入任何内容。

我正在考虑的另一种方法是扩展 OpenFileDialog 类并使其行为符合我的喜好,但这似乎很复杂。

有什么好的方法可以做到这一点吗?

【问题讨论】:

  • 你正在调用 Show,如果你想让你的表单表现得像一个模式对话框,你应该调用 ShowDialog。
  • 另外,也不需要 IsOK 属性。只需将按钮属性 DialogResult 设置为 DialogResult.OK。在按钮事件处理程序中检查您是否有文件,如果没有,请将表单 DialogResult 属性更改为 DialogResult.None。这将允许您对 OpenFileDialog 使用相同的代码示例
  • 完美,谢谢。我没有意识到您可以将表单称为模式对话框,我认为您必须实现该行为或其他东西。干杯

标签: c# openfiledialog


【解决方案1】:

Form 控件有一个DialogResult 属性,其值从ShowDialog 方法返回。因此,您所要做的就是在对话框表单中添加一个Ok 按钮,然后添加代码以在该按钮后面设置DialogResult(并关闭表单)。

例如:

public partial class OpenDatabaseDialog : Form
{
    public OpenDatabaseDialog()
    {
        InitializeComponent();
    }

    private void btnOk_Click(object sender, EventArgs e)
    {
        // Set any properties necessary that indicate the user's selections

        // User clicked 'Ok' so set our result (which will also close the form)
        this.DialogResult = DialogResult.OK;
    }
}

然后,在您的主窗体代码中,您可以像捕获任何其他对话框一样捕获结果,方法是调用 ShowDialog 并捕获返回值。

主窗体:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var openDbDialog = new OpenDatabaseDialog();

        // Show the form as a dialog and capture the result
        if (openDbDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show("You clicked 'Ok' to close the dialog");
        }
        else
        {
            MessageBox.Show("You closed the dialog some other way");
        }
    }
}

【讨论】:

  • 你不需要调用这个。如果你设置了表单的DialogResult属性就关闭。当你退出事件处理程序时它会自动关闭(除非你设置了特殊的 DialogResult.None)
  • @Steve 谢谢,我没有意识到这一点!更新的答案。
猜你喜欢
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多