正确使用 DialogResult [英] Using DialogResult Correctly

查看:47
本文介绍了正确使用 DialogResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对我最近提出的一个问题(此处)的回答中,Hans Passant 表示我应该设置 DialogResult 来关闭我的表单而不是 form.Close() 虽然我似乎无法找出原因?

如果我没看错的话,MSDN 文档指出,这样做只会隐藏表单,而不是我认为 .Close() 会正确处理它?<​​/p>

从文档中提取.

<块引用>

当用户单击对话框的关闭按钮或设置 DialogResult 属性的值时,不会自动调用 Close 方法.相反,窗体被隐藏并且可以再次显示而无需创建对话框的新实例.由于这种行为,当您的应用程序不再需要表单时,您必须调用该表单的 Dispose 方法.

另一方面,Microsoft 创建了一个支持页面,说明如何使用 DialogResult 属性并在此的验证它有效"部分中指出单击如此"将关闭表单.

所以我的问题有两个,我应该继续使用 Close 还是 DialogResult ;并关闭或隐藏表单对话框结果.从我下面制作的代码(一个带有两个按钮的简单表单)来看,它似乎确实是隐藏的,只是因为 this.Close() 上的断点被击中..(with this.Close() 注释了,表单还是消失了,只是不确定是否隐藏)

 public Form1(){初始化组件();button1.Click += (s, e) =>{//我编辑了我的问题以包括使用using(Form1 form = new Form1()){form.ShowDialog();}};button2.Click += (s, e) =>{this.DialogResult = DialogResult.OK;this.Close();};}

解决方案

当您使用 ShowDialog 打开模式对话框时,调用代码将被阻止,直到被调用的窗体关闭或隐藏.如果您想读取被调用表单的一些公共属性并希望基于单击确定"或取消"按钮执行某些操作(例如将数据保存到数据库或文件),那么您需要知道用户是否想要做与不做的动作.ShowDialog() 方法返回的 DialogResult 允许您采取适当的操作...

例如

using (Form1 form = new Form1()){DialogResult dr = form.ShowDialog();如果(博士 == DialogResult.OK){字符串 custName = form.CustomerName;SaveToFile(custName);}}

要添加到此答案的重要一点是 DialogResult 属性存在于 Form 类和 Button 类中.将按钮的 DialogResult 属性(通过代码或设计器)设置为不同于 DialogResult.None 的值是激活表单重要行为的关键.如果您单击设置了该属性的按钮,则表单引擎会将 Buttons 属性的值传输到表单并触发表单的自动关闭,重新激活调用者代码.如果您在按钮单击上有一个事件处理程序,那么您可以运行代码来验证表单的输入并强制表单保持打开状态,覆盖表单的 DialogResult 属性将其设置回 DialogResult.None

例如,在模态显示的表单中,您可以:

//使用 DialogResult.OK 设置的 OK 按钮的事件处理程序public void cmdOK_Click(对象发送者,EventArgs e){//检查表单数据的代码和//最终显示错误信息.bool isFormDataValid = ValidateFormData();//如果数据无效,则强制表单保持打开状态如果(!isFormDataValid)this.DialogResult = DialogResult.None;}

In an answer to a recent question I had (Here), Hans Passant stated that I should set the DialogResult to close my forms instead of form.Close() although I cannot seem to find out why?

If I've read correctly, the MSDN documentation states that doing this will just hide the form instead of correctly disposing it which I believed .Close() to do?

Extract from documentation.

The Close method is not automatically called when the user clicks the Close button of a dialog box or sets the value of the DialogResult property. Instead, the form is hidden and can be shown again without creating a new instance of the dialog box. Because of this behavior, you must call the Dispose method of the form when the form is no longer needed by your application.

On the other hand, Microsoft has created a support page that says how to use DialogResult property and in the "Verify It Works" section of this it states that clicking so will Close the form.

So my question is two fold, should I continue to use Close or DialogResult instead; and does dialog result close or hide a form. From the code I made below (a simple form with two buttons), it would seem that it is indeed hidden only as a breakpoint on this.Close() is hit..(with this.Close() commented, the form still disappears, just not sure whether hidden or not)

    public Form1()
    {
        InitializeComponent();
        button1.Click += (s, e) =>
            {
                 //I edited my question to include using
                using(Form1 form = new Form1())
                {
                    form.ShowDialog();
                }

            };
        button2.Click += (s, e) => 
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            };
    }

解决方案

When you open a modal dialog with ShowDialog, the calling code is blocked until the form called closes or hides. If you want to read some public properties of the called form and want to do things (for example save data to a database or to a file) based on the click on the OK or Cancel button, then you need to know if the user wants to do the action or not. The DialogResult returned by the ShowDialog() method allows you to take the appropriate actions...

So for example

using (Form1 form = new Form1())
{
    DialogResult dr = form.ShowDialog();
    if(dr == DialogResult.OK)
    {
        string custName = form.CustomerName;
        SaveToFile(custName);
    }
    
}

An important thing to add to this answer is the fact that the DialogResult property exists both on the Form class and in the Button class. Setting the button's DialogResult property (both via code or designer) to a value different from DialogResult.None is the key to activate an important behavior for forms. If you click a button with that property set then the Forms Engine transfers the value of the Buttons property to the Forms one and triggers the automatic closure of the form reactivating the caller code. If you have an event handler on the button click then you can run code to validate the form's inputs and force the form to stay open overriding the form's DialogResult property setting it back to DialogResult.None

For example, in the modally showed form you can have:

// Event handler for the OK button set with DialogResult.OK
public void cmdOK_Click(object sender, EventArgs e)
{
     // Your code that checks the form data and
     // eventually display an error message.
     bool isFormDataValid = ValidateFormData();

     // If data is not valid force the form to stay open
     if(!isFormDataValid)
        this.DialogResult = DialogResult.None;
}

这篇关于正确使用 DialogResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆