Toto
Toto

Reputation: 960

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:

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.

What am I missing ?

Upvotes: 0

Views: 1707

Answers (1)

Steve
Steve

Reputation: 216243

Calling Close will set the DialogResult property to Cancel overriding whatever you set before the call to Close. You can easily verify this using the debugger and inspecting the value of this.DialogResult before and after the call to Close.

But, when a form is shown modally you don't need and you shouldn't normally call Close. You can hide the form just setting the property DialogResult causing your code to exit from the call to ShowDialog.

A form shown modally is not closed when you set the DialogResult property but only hidden. 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. (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;
}

Upvotes: 2

Related Questions