How to send data between multiple forms in C# windows

How to send data from one form to another form or share data between multiple forms. we will learn How to pass data from one form to another form in Windows forms applications using C#.

In C# windows application. The value we want to transfer from one form to another, or we want the value from the child form to display in the parent form, we can use a simple way by declaring the public static variable in the child form. In the case of vise versa — you want to pass the data to child form — you can use the public static variable in the parent form.

Send data between multiple forms in C# windows

Let’s use the following procedure to create a Windows Forms application.

Step 1:

In Visual Studio select “File” -> “New” -> “Project…” then select C# Windows Forms Application then click Ok.

Step 2:

Drag and drop a Label and a TextBox from the Toolbox. I created a Form with 3 Labels and a TextBox as shown in the following figure.

Step 3:

I have a Name, Fname, and Address Label on the form. So I use three global variables. Write the following code in Form1.cs.

public static string SetValueForText1 = ""; 
public static string SetValueForText2 = ""; 
public static string SetValueForText3 = "";

Step 4:

Add another Windows Forms form using Project –> Add Windows Form then click on Add.

Step 5:

After creating the form double-click on the Submit button on the Windows Form1 and write the code:

private void button1_Click(object sender, EventArgs e)
{
SetValueForText1 = textBox1.Text;
SetValueForText2 = textBox2.Text;
SetValueForText3 = textBox3.Text;
Form2 frm2 = new Form2();
frm2.Show(); 
}

Step 6:

Drag and Drop 3 Labels from the Toolbox onto Form2. Change their text from the property window as following Name, Fname, and Address.

Step 7:

Double-click on Form2 and write the following code:

private void Form2_Load(object sender, EventArgs e)
{
lable1.Text = Form1.SetValueForText1;  
lable2.Text = Form1.SetValueForText2;
lable3.Text = Form1.SetValueForText3;
}

Step 8:

Now press F5 to run the application. Fill in Form1 and click on Submit. The data will pass from Form1 to Form2.

Note:

You can pass the data from one form to any number of forms by creating a public static variable and object to the form to which you are going to transfer the data.
You can also create a .cs file as common and you can declare and define variables in that common class file and can access them anywhere in the project.

In this way, we learn how we can transfer or share the data between multiple forms in C#.