Passing values between a parent form and a child form – using c# in winforms

There’s a few ways to do this, here’s one method

(important bits shown in boldface):

(1) in the ‘parent’ form do this:

….
namespace OnlineNotificationsRegistration
{
    /// <summary>
    /// ONS pre-registration details capture program
    /// </summary>
    public partial class ONSRegoForm : Form
    {
          public string StrTest
          {
                get { return textBox1.Text; }
                set { textBox1.Text = value; }
          }

        public ONSRegoForm()
        {
        ….

and then when launching the child form, do this:

        …..
           DALSinfo d = new DALSinfo();
           d.MyParentForm = this;
        d.ShowDialog();
    }

(2) in the ‘child’ form, do this

…..
namespace OnlineNotificationsRegistration
{
    public partial class DALSinfo : Form
    {
    /// <summary>
    /// provides reference to parent form
    /// </summary>
    
     public ONSRegoForm MyParentForm;
….

then to reference parent form do this:

    private void DALSinfo_FormClosing(object sender, FormClosingEventArgs e)
    {
        MyParentForm.StrTest = rowCount.ToString();
    }

Advertisements