简体   繁体   English

自定义窗体始终返回DialogResult.Cancel

[英]Custom form always return DialogResult.Cancel

I have implemented a form that I use as a DialogBox, I use it using the ShowDialog method and retrieve its DialogResult, which is set by the two buttons it implements: 我已经实现了一个用作对话框的窗体,我使用了ShowDialog方法来使用它并检索它的DialogResult,这由它实现的两个按钮设置:

DialogResult dialogResult = registerForm.ShowDialog(); 

private void btRegister_Click(object sender, EventArgs e)
{
    DialogResult = !string.IsNullOrEmpty(Key) ? DialogResult.OK : DialogResult.None;
    Close();
}

private void btCancel_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.Cancel;
    Close();
}

The thing is, the value returned by ShowDialog is always Cancel, even when the DialogResult property has been set to None or OK. 问题是,即使DialogResult属性设置为None或OK,ShowDialog返回的值也始终为Cancel。

What am I missing ? 我想念什么?

Calling Close will set the DialogResult property to Cancel overriding whatever you set before the call to Close. 调用Close将把DialogResult属性设置为Cancel,覆盖您在调用Close之前设置的内容。 You can easily verify this using the debugger and inspecting the value of this.DialogResult before and after the call to Close. 您可以使用调试器并在调用Close之前和之后轻松检查this.DialogResult的值来验证这一点。

But, when a form is shown modally you don't need and you shouldn't normally call Close. 但是,当窗体以模态显示时,您不需要,通常不应调用Close。 You can hide the form just setting the property DialogResult causing your code to exit from the call to ShowDialog. 您可以仅设置属性DialogResult来隐藏表单,从而使您的代码从对ShowDialog的调用中退出。

A form shown modally is not closed when you set the DialogResult property but only hidden. 设置DialogResult属性时,以模态显示的窗体不会关闭,而只是隐藏的。 This allows the calling code to access the form's properties and take appropriate actions. 这使调用代码可以访问表单的属性并采取适当的措施。

Also, it is good practice to enclose the form's initialization call in a using statement to propertly Dispose the modal form when you don't need it anymore. 另外,优良作法是将窗体的初始化调用包含在using语句中,以在不再需要模式窗体时适当地处置它。 (Of course this is not the case with forms shown not-modally) (当然,不是以非模态形式显示表单的情况并非如此)

using(RegisterForm registerForm = new RegisterForm())
{
     DialogResult dialogResult = registerForm.ShowDialog(); 
     if(dialogResult == DialogResult.OK)
     {
        .....
     }
}  
// <== At this point the registerForm instance has been Closed and Disposed 
//     It is no more in scope and you cannot use it in any way
....
private void btRegister_Click(object sender, EventArgs e)
{
    DialogResult = !string.IsNullOrEmpty(Key) ? 
                    DialogResult.OK : DialogResult.None;
}

private void btCancel_Click(object sender, EventArgs e)
{
    DialogResult = DialogResult.Cancel;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM