How to Pass Data Between the Forms Using the Static Concept

Introduction:

This article shows how to pass data between the forms using the static concept. It's easy to understand.

1.gif
 
Code: Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    public static Parent p;
    private void btn_parentOpen_Click(object sender, EventArgs e)
    {
        p = new Parent();
        p.Show();
    }       
}

First we have created public and static obj of Parent in the Form1 Click event. The reason for making static object p is so that we can use this Single object during the entire application and we can pass the data to the Parent form by using this object. If we don't make the static object then we are not able to pass data. (It is possible if you use delegates or a constructor but we are talking about how to pass data with static concept.) 

Code: Parent

public partial class Parent : Form
{
    public Parent()
    {
        InitializeComponent();
    }
    private void btnAdd_Click(object sender, EventArgs e)
    {
        Child c = new Child();           
        c.ShowDialog();
    }
}

In the Parent form we open the child form where we fill the data and display the filled data to the Parent form. It means we pass data child form the parent form. 

Code: Child

public partial class Child : Form
{
    public Child()
    {
        InitializeComponent();
    }
    private void btn_ok_Click(object sender, EventArgs e)
    {
        Form1.p.txt_id.Text = txt_id.Text;
        Form1.p.txt_name.Text = txt_name.Text;
        Form1.p.txt_standard.Text = txt_standard.Text;
        Form1.p.txt_divison.Text = txt_divison.Text;
        this.Close();
    }
}

Now, our main working is started. When the Child form is filled then all data should display in the Parent Form. To do so we use the object of Parent form. By using this object we access the elements of Parent class and display appropriate data. Since the object of form Parant p is static we can use it directly by class name.
We have made p object of Parent form in the Form1 class so it is used like this: Form1.p.

And now you can control all the public controls of Parent form or in other words you are able to pass the data from Child form to Parent Form as I did in the btn_ok's click event.