Question

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();
            };
    }
Était-ce utile?

La solution

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;
}

Autres conseils

Whether you call Close or set the DialogResult property is not really the issue. You just need to make sure to call Dispose. I prefer doing this with a using block:

using (Form1 form = new Form1())
{
    form.ShowDialog();
}

I originally thought that you could call ShowDialog on a Form that has already had its Close method called. This is not the case. If you show the form modally with ShowDialog, it doesn't seem to matter whether it is closed as a result of the Close method, or setting the DialogResult property. It would seem that setting the DialogResult is just a short-cut for closing the Form.

But whether you call Close or set the DialogResult property, the key is to make sure that you call Dispose() or put your form in a using block.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top