How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.
I launched the child using:
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.
I launched the child using:
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
If you are displaying child form as a modal dialog box, you can set DialogResult property of child form with a value from the DialogResult enumeration which in turn hides the modal dialog box, and returns control to the calling form. At this time parent can access child form's data to get the info that it need.
For more info check this link: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx
For Picrofo EDY
It depends, if you use the
ShowDialog()
as a way of showing your form and to close it you use the close button instead ofthis.Close()
. The form will not be disposed or destroyed, it will only be hidden and changes can be made after is gone. In order to properly close it you will need theDispose()
orClose()
method. In the other hand, if you use theShow()
method and you close it, the form will be disposed and can not be modified after.Create a property (or method) on
FormOptions
, sayGetMyResult
:I think the easiest way is to use the Tag property in your FormOptions class set the Tag = value you need to pass and after the ShowDialog method read it as
If you're just using formOptions to pick a single value and then close, Mitch's suggestion is a good way to go. My example here would be used if you needed the child to communicate back to the parent while remaining open.
In your parent form, add a public method that the child form will call, such as
Next, when you need to launch the child window from the parent, use this code:
In the child form, use this code to pass a value back to the parent:
The code in this example would be better used for something like a toolbox window which is intended to float above the main form. In this case, you would open the child form (with .TopMost = true) using .Show() instead of .ShowDialog().
A design like this means that the child form is tightly coupled to the parent form (since the child has to cast its owner as a ParentForm in order to call its NotifyMe method). However, this is not automatically a bad thing.
Use public property of child form
Use events
Use public property of main form
Use object Control.Tag; This is common for all controls public property which can contains a System.Object. You can hold there string or MyClass or MainForm - anything!