Many times, we need to send data from parent form to child form and vice versa. In the below blog, I will demonstrate both.
For this, you need to create a desktop application and 2 WinForms.
The above picture is form1.cs that represents the Parent form.
Here, we write a name and click on the button to send the data to the child form to get the age.
- private void send_btn_Click(object sender, EventArgs e)
- {
- string name = name_tb.Text;
- Child form = new Child(name);
- form.ShowDialog();
- result_tb.Text = form.SendData();
-
- }
You need to create an instance of the child form with 1 parameter constructor and send name to the child.
In Child.cs, you need to create a parameterized constructor.
- public Child (string name)
- {
- InitializeComponent();
- name_tb.Text = name;
- }
And assign the name to the textbox which is present in the Child form.
Now, to send the Age back to parent form, you need to create a Public method in Child.cs.
- public string SendData()
- {
- return "Age of " + name + " is " + age_tb.Text;
- }
Now, call this method in Form1.cs to get the value of Age.
- private void send_btn_Click(object sender, EventArgs e)
- {
- string name = name_tb.Text;
- Child form = new Child(name);
- form.ShowDialog();
- result_tb.Text = form.SendData();
-
- }
That's all.
Summary
To send data from Parent to Child form you need to create a parameterized constructor.
To send data from Child to Parent form you need to create a public method in Child class and use the method in Parent class to get the return value.
Watch the video tutorial by clicking on this
link.