How to pass data between two Forms in C#(Parent to child Form, and vice versa)

Lionsure 2020-08-28 Original by the website

In Winforms development, sometimes the parent Form needs to pass arguments to the child Form, and sometimes the child Form needs to pass some data back to the parent Form after the execution of child Form. It is really a courtesy. You pass it to me. I can't help but pass it to you.

Passing data from the parent Form to the child Form is very simple, just like a normal method; the child Form to pass the parent Form is a bit troublesome, you need to define more variables, but there are several ways to pass. Let's share the example of the parent Form passing data to the child Form and the example of the child Form passing data to the parent Form.

 

1. How to pass data between two Forms in C#(Parent Form to child Form)

If the child Form is also displayed when the parent Form is displayed, the parent Form code:

private void Form1_Load(object sender, EventArgs e)
       {
              string userName = "testuser";
              SubForm sf = new SubForm(userName);
              sf.Show();
       }

 

Subform code:

private string userName;

public SubForm(string _UserName)
       {
              userName = _UserName;
              InitializeComponent();
       }

 

 

2. How to pass data between two Forms in C#(Child Form to parent Form)

Since the child Form cannot create an instance of the parent Form, the above method cannot be used. The parent Form can be defined in the child Form, and the parent Form defined in the child Form is initialized with the object of parent Form when the parent Form calls the child Form, the subform execution ends and assigns the data to the members of the parent Form, the code is as follows:

Parent Form code:

public string param;

private void btnParentToSubForm_Click(object sender, EventArgs e)
       {
              SubForm sf = new SubForm(this);
              sf.ShowDialog();
              if (sf.DialogResult == DialogResult.OK)
              {
                     MessageBox.Show(param);
              }
       }

 

Subform code:

private Form1 f1;
       private string subParam;

public SubForm(Form1 f)
       {
              f1 = f;
              InitializeComponent();
       }

private void button1_Click(object sender, EventArgs e)
       {
              this.subParam = "Pass to the parent Form";
              f1.param = this.subParam;
              this.DialogResult = DialogResult.OK;
       }

In addition to this method, you can also use the method of defining global variables, you can also use events to achieve, but it is more troublesome.

 

The above code is tested by Visual Studio and can be used with slight changes according to actual application requirements.