"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Method for efficient return value to parent MDI form for C# child form

Method for efficient return value to parent MDI form for C# child form

Posted on 2025-04-14
Browse:261

How to Efficiently Return Values from a C# Child Form to its Parent MDI Form?

Returning Values from Forms in C#

In a scenario where a child form (frmHireQuote) is opened from a parent MDI form (frmMainMDI) using ShowDialog(), how can we efficiently pass values from the child form back to specific text boxes on the parent form, while ensuring that the values are returned to the correct parent instance?

Solution

To return values from the child form (frmImportContact) to the parent form (frmHireQuote), follow these steps:

  1. Create Public Properties in the Child Form: Define public properties in the child form to store the values to be returned. For example:
public string ReturnValue1 { get; set; }
public string ReturnValue2 { get; set; }
  1. Set Properties in the Child Form: When the user clicks the OK button on the child form, set the public properties with the desired values. For example:
private void btnOk_Click(object sender, EventArgs e)
{
    this.ReturnValue1 = "Something";
    this.ReturnValue2 = DateTime.Now.ToString(); //example
    this.DialogResult = DialogResult.OK;
    this.Close();
}
  1. Retrieve Properties in the Parent Form: In the parent form (frmHireQuote), when opening the child form, use a using block to capture the return result:
using (var form = new frmImportContact())
{
    var result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        string val = form.ReturnValue1; //values preserved after close
        string dateString = form.ReturnValue2;
        //Do something here with these values

        //for example
        this.txtSomething.Text = val;
    }
}

By following these steps, you can effectively return values from a child form to specific text boxes on the parent form, ensuring that the values are retrieved from the correct instance of the parent form.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3