在关闭子对话框按钮后使父对话框按钮保持打开状态

本文关键字:对话框 按钮 状态 | 更新日期: 2023-09-27 18:30:35

我在使用 ShowDialog() 后保持父窗体打开直到关闭时遇到问题。

我一直在尝试这个,但无法得到。我认为我可能错过了一些简单的东西。你能帮我注册这个吗?

问题是,我有表格 1,按下一个按钮,表格 2 打开。我在表单 2 中进行了一些验证,并检查了验证。如果验证未通过,我将打开一个"对话框"窗体,其中包含"重试并取消"。如果我按重试,控件应返回到窗体 2,窗体 2 不应关闭。如果按"取消",对话框窗体和窗体 2 都应关闭。现在,无论我按什么,两种形式都关闭了。

我在网上看过,找不到任何解决方案。完成了这个解决方案,但两个表格对我来说仍然关闭。为什么关闭嵌套的子对话框也会关闭父对话框?

我的代码:(示例示例场景)

表格 1:

private void button1_Click(object sender, EventArgs e)
{
    Form2 testForm = new Form2();
    DialogResult dialogResult = new DialogResult();
    dialogResult = testForm.ShowDialog(this);
    if(dialogResult == DialogResult.OK)
    {
        //Do something
    }
}

表格 2:

private void button1_Click(object sender, EventArgs e)
{
    DialogResult validDataResult = MessageBox.Show("Invalid Data Entered. Please provide the correct data."
            , "Data Management"
            , MessageBoxButtons.RetryCancel);
    if (validDataResult == DialogResult.Cancel)
    {
        this.Close();
    }
}

在关闭子对话框按钮后使父对话框按钮保持打开状态

在 Form2 中.cs执行验证,然后
(假设验证OK是检查的真/假结果)

if(validationOK == false)
{
    // Ask retry or cancel to the user
    if(DialogResult.Cancel == MessageBox.Show("Validation Fail", "Validation failed, press retry to do it againg", MessageBoxButtons.RetryCancel))
        this.DialogResult.Cancel; // Set the dialog result on form2. This will close the form.
    // if you have the validation done in a button_click event and that button has its
    // property DialogResult set to something different than DialogResult.None, we need
    // to block the form2 from closing itself.
    // uncomment this code if the above comment is true
    // else
    //    this.DialogResult = DialogResult.None;
}

必须先设置 Form2DialogResult,然后才能调用 this.Close() 。否则,它仍然是默认值。(下面的代码只是对实际双关逻辑的猜测,因为您没有指定)

表格2.cs:

if (validDataResult == DialogResult.Cancel)
    DialogResult = DialogResult.Cancel;
else
    DialogResult = DialogResult.OK;
Close();

表格1.cs:

if(dialogResult == DialogResult.OK)
{
    Close();
}
else
{
    //Do something
}