Using Properties To pass fields between Dialogs

N

Nick

A lot of people say to use properties to pass variables between a main
dialog and a subdialog like so:

Form form = new Form();
if (form.ShowDialog()==DialogResult.OK)
{
string str = form.StrinValue;
}

but how should I close the dialog since if I do the following in the
sub form when the user presses OK, then I am destroying the instance
and so the property will not be set correctly or will not exist. How
should I 'close' the form??

private void buttonOK_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}

Also is there any difference between Show and showDialog in the way
that I should close them?

Thanks for any help.
Nick
 
J

Jay B. Harlow [MVP - Outlook]

Nick,
I allow Windows Forms to close the dialog, instead of coding DialogResult &
Close in the buttonOK.Click event handler.

I set the buttonOk.DialogResult property to DialogResult.OK, I then set the
Form.AcceptButton property to buttonOk. Like wise for buttonCancel, I set
buttonCancel.DialogResult to DialogResult.Cancel and Form.CancelButton to
buttonCancel.

Windows Forms will then take care of closing the form and returning the
appropriate result. No need for the buttonOk.Click event handler per se.
Also is there any difference between Show and showDialog in the way
that I should close them?
When you use Form.ShowDialog to display a dialog box, the form does not call
Dispose when you call Form.Close, so as to allow you to get the values of
your properties, if you use Form.Dispose you should call Form.Dispose when
you are done. I would use the using statement. When you use Form.Show,
Form.Close does call Form.Dispose.

Hope this helps
Jay
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Nick,

That the form is closed (nor yet opened) does not mean it will be
destroyed, you can access its properties as with any other object you use.

private void buttonOK_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}

This is fine AFAIK.
Also is there any difference between Show and showDialog in the way
that I should close them?

No really.

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top