How do I pass a value from a child back to the parent form?

C#.NetWinformsParent Child

C# Problem Overview


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();

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

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;

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

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.

Solution 7 - C#

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.

Solution 8 - C#

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

Solution 9 - C#

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

Solution 10 - C#

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.

Solution 11 - C#

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;

Solution 12 - C#

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.

Solution 13 - C#

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?!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJayne MView Question on Stackoverflow
Solution 1 - C#Mitch WheatView Answer on Stackoverflow
Solution 2 - C#MusiGenesisView Answer on Stackoverflow
Solution 3 - C#stiduckView Answer on Stackoverflow
Solution 4 - C#Ali ErsözView Answer on Stackoverflow
Solution 5 - C#abatishchevView Answer on Stackoverflow
Solution 6 - C#ChagbertView Answer on Stackoverflow
Solution 7 - C#Bravo MikeView Answer on Stackoverflow
Solution 8 - C#ghfarzadView Answer on Stackoverflow
Solution 9 - C#user889030View Answer on Stackoverflow
Solution 10 - C#kennyView Answer on Stackoverflow
Solution 11 - C#AhmedView Answer on Stackoverflow
Solution 12 - C#OdinView Answer on Stackoverflow
Solution 13 - C#mahdi yousefiView Answer on Stackoverflow