52

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();
abatishchev
  • 98,240
  • 88
  • 296
  • 433

13 Answers13

71

Create a property (or method) on FormOptions, say GetMyResult:

using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();

    string result = formOptions.GetMyResult;

    // do what ever with result...
}
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • you solution only works after the dialog is closed, how about passwing message to the parent form and back when the child form is still openned – Smith Sep 22 '15 at 10:07
  • 1
    @Smith you can't. Not this way. Also it's not wanted that way because ShowDialog() waits until the Form finishes – slow Mar 22 '18 at 08:58
36

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

public void NotifyMe(string s)
{
    // Do whatever you need to do with the string
}

Next, when you need to launch the child window from the parent, use this code:

using (FormOptions formOptions = new FormOptions())
{
    // passing this in ShowDialog will set the .Owner 
    // property of the child form
    formOptions.ShowDialog(this);
}

In the child form, use this code to pass a value back to the parent:

ParentForm parent = (ParentForm)this.Owner;
parent.NotifyMe("whatever");

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.

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
  • I tried your method, however it didn't work for me. This is error I get on parent.NotifyMe(). Can you help me figure out what went wrong? The function is public in parent. System.NullReferenceException was unhandled HResult=-2147467261 Message=Object reference not set to an instance of an object. – SLearner Jun 03 '13 at 16:50
  • 1
    @shashlearner: I assume you're calling `formOptions.ShowDialog();` instead of `formOptions.ShowDialog(this);` as I specified in the post. If you don't pass `this` in the call, the `.Owner` property of the child form will be `null` and you'll get a null reference exception. – MusiGenesis Jun 04 '13 at 16:14
  • Excellent Just what i was looking for – Zujaj Misbah Khan May 25 '20 at 17:10
23

You can also create a public property.

// Using and namespace...

public partial class FormOptions : Form
{
    private string _MyString;    //  Use this
    public string MyString {     //  in 
      get { return _MyString; }  //  .NET
    }                            //  2.0

    public string MyString { get; } // In .NET 3.0 or newer

    // The rest of the form code
}

Then you can get it with:

FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();

string myString = formOptions.MyString;
stiduck
  • 510
  • 4
  • 9
10

You can also create an overload of ShowDialog in your child class that gets an out parameter that returns you the result.

public partial class FormOptions : Form
{
  public DialogResult ShowDialog(out string result)
  {
    DialogResult dialogResult = base.ShowDialog();

    result = m_Result;
    return dialogResult;
  }
}
MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
Ali Ersöz
  • 15,860
  • 11
  • 50
  • 64
  • 1
    I like this. Dialog windows have always felt a little weird to me, since you're showing a window and then getting its info after it's gone. This approach shows the window and retrieves the info all at once. – MusiGenesis Nov 11 '08 at 14:32
3

Use public property of child form

frmOptions {
     public string Result; }

frmMain {
     frmOptions.ShowDialog(); string r = frmOptions.Result; }

Use events

frmMain {
     frmOptions.OnResult += new ResultEventHandler(frmMain.frmOptions_Resukt);
     frmOptions.ShowDialog(); }

Use public property of main form

frmOptions {
     public frmMain MainForm; MainForm.Result = "result"; }

frmMain {
     public string Result;
     frmOptions.MainForm = this;
     frmOptions.ShowDialog();
     string r = this.Result; }

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!

frmOptions {
     this.Tag = "result": }
frmMain {
     frmOptions.ShowDialog();
     string r = frmOptions.Tag as string; }
abatishchev
  • 98,240
  • 88
  • 296
  • 433
2

Well I have just come across the same problem here - maybe a bit different. However, I think this is how I solved it:

  1. in my parent form I declared the child form without instance e.g. RefDateSelect myDateFrm; So this is available to my other methods within this class/ form

  2. next, a method displays the child by new instance:

    myDateFrm = new RefDateSelect();
    myDateFrm.MdiParent = this;
    myDateFrm.Show();
    myDateFrm.Focus();
    
  3. my third method (which wants the results from child) can come at any time & simply get results:

    PDateEnd = myDateFrm.JustGetDateEnd();
    pDateStart = myDateFrm.JustGetDateStart();`
    

    Note: the child methods JustGetDateStart() are public within CHILD as:

    public DateTime JustGetDateStart()
    {
        return DateTime.Parse(this.dtpStart.EditValue.ToString());
    }
    

I hope this helps.

Fabian N.
  • 3,807
  • 2
  • 23
  • 46
Chagbert
  • 722
  • 7
  • 16
1

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 of this.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 the Dispose() or Close() method. In the other hand, if you use the Show() method and you close it, the form will be disposed and can not be modified after.

Paolo Bernasconi
  • 2,010
  • 11
  • 35
  • 54
Bravo Mike
  • 11
  • 1
1

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

ghfarzad
  • 11
  • 1
1

i had same problem i solved it like that , here are newbies step by step instruction

first create object of child form it top of your form class , then use that object for every operation of child form like showing child form and reading value from it.

example

namespace ParentChild
{
   // Parent Form Class
    public partial class ParentForm : Form
    {
        // Forms Objects
        ChildForm child_obj = new ChildForm();


        // Show Child Forrm
        private void ShowChildForm_Click(object sender, EventArgs e)
        {
            child_obj.ShowDialog();
        }

       // Read Data from Child Form 
        private void ReadChildFormData_Click(object sender, EventArgs e)
        {
            int ChildData = child_obj.child_value;  // it will have 12345
        }

   }  // parent form class end point


   // Child Form Class
    public partial class ChildForm : Form
    {

        public int child_value = 0;   //  variable where we will store value to be read by parent form  

        // save something into child_value  variable and close child form 
        private void SaveData_Click(object sender, EventArgs e)
        {
            child_value = 12345;   // save 12345 value to variable
            this.Close();  // close child form
        }

   }  // child form class end point


}  // name space end point
user889030
  • 4,353
  • 3
  • 48
  • 51
0

When you use the ShowDialog() or Show() method, and then close the form, the form object does not get completely destroyed (closing != destruction). It will remain alive, only it's in a "closed" state, and you can still do things to it.

Darshana
  • 2,462
  • 6
  • 28
  • 54
Odin
  • 1
  • I think that you mean Hide(). I do not really think that the form will be capable for changes after closing it, unless if you are accessing it externally. – Picrofo Software Oct 19 '12 at 21:10
0

Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.

Community
  • 1
  • 1
kenny
  • 21,522
  • 8
  • 49
  • 87
0

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

myvalue x=(myvalue)formoptions.Tag;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Ahmed
  • 7,148
  • 12
  • 57
  • 96
  • 2
    I prefer not to use the Tag on classes that I have control of (i.e. where I can add a property). I think it is cleaner to use a property with a proper name and type. – Xavier Poinas Jun 23 '10 at 07:51
0

The fastest and more flexible way to do that is passing the parent to the children from the constructor as below:

  1. Declare a property in the parent form:

    public string MyProperty {get; set;}

  2. Declare a property from the parent in child form:

    private ParentForm ParentProperty {get; set;}

  3. Write the child's constructor like this:

      public ChildForm(ParentForm parent){
          ParentProperty= parent;
      }
    
  4. Change the value of the parent property everywhere in the child form:

    ParentProperty.MyProperty = "New value";

It's done. the property MyProperty in the parent form is changed. With this solution, you can change multiple properties from the child form. So delicious, no?!

mahdi yousefi
  • 807
  • 1
  • 9
  • 15