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, Fname and Address Label on the form. So I use three global variables. Write the following code in the Form1.cs.

  1. public static string SetValueForText1 = "";  
  2. public static string SetValueForText2 = "";  
  3. public static string SetValueForText3 = ""

Step 4

Add another Windows Forms form using Project --> Add Windows Form thenn 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:

  1. private void button1_Click(object sender, EventArgs e)  
  2. {  
  3.    SetValueForText1 = textBox1.Text;  
  4.    SetValueForText2 = textBox2.Text;  
  5.    SetValueForText3 = textBox3.Text;  
  6.   
  7.    Form2 frm2 = new Form2();  
  8.    frm2.Show();  

Step 6

Drag and Drop 3 Labels from the Toolbox onto Form2.

Toolbox on Form2

Step 7

Double-click on Form2 and write the code:

  1. private void Form2_Load(object sender, EventArgs e)  
  2. {  
  3.    label1.Text = Form1.SetValueForText1;  
  4.    label2.Text = Form1.SetValueForText2;  
  5.    label3.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.

pass From Form1 to Form 2

Up Next
    Ebook Download
    View all
    Learn
    View all