How to Pass Data One Form to Another in Windows Form Application

Introduction

In this tutorial, we will learn how to pass data from one form to another form in Windows Forms applications using C#.

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.

window form application

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.

ToolBox

Step 3. I have a Name, Name, and Address Label on the form. So I use three global variables. Write the following code in the 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.

Windows Form

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 Form 2.

Toolbox on Form2

Step 7. Double-click on Form 2 and write the code.

private void Form2_Load(object sender, EventArgs e)  
{  
   label1.Text = Form1.SetValueForText1;  
   label2.Text = Form1.SetValueForText2;  
   label3.Text = Form1.SetValueForText3;  
} 

Step 8. Now press F5 to run the application.

Fill in Form 1 and click on Submit. The data will pass from Form 1 to Form 2.

pass From Form1 to Form 2

 


Similar Articles