Data Passing Between Forms

Introduction

Sometimes you may have encountered a problem requiring you to pass data from one form to another in C# WinForms. I have also encountered this problem and searched it on Google. Now, I have some solutions.

program

So, I will share four different methods to pass data from one form to another. But in this article I will only focus on the first method, that is using the constructor.

  1. With constructor
  2. With objects
  3. With properties
  4. With delegates

We will now briefly discuss the preceding methods.

Step 1

First create a new project and then select C# > Windows Form. Now you have the following Form1.

form

Step 2

Drag and drop a button and TextBox in Form1.

Step 3

Click on Solution Explorer and right-click on WindowsFormApplication1 then select Add > New item. Then in the Add New Item winidow select Windows Forms > Windows Form then select Add.

Add

windows form

Step 4

Drag and drop a Label into Form2.

With Constructor:

It is a simple method in which I will form a constructor of Form2 with a parameter. When Form2 is called, the constructor runs automatically. I passed the string from TextBox1 of Form1 to Form2.

Step 1

Create a constructor in Form2.

  1. public Form2(string strTextBox)  
  2. {  
  3.    InitializeComponent();  
  4.    label1.Text=strTextBox;  
  5. }  
Step 2

Use the following code in Form1's Button Handler for Form2.
  1. private void button1_Click(object sender, System.EventArgs e)  
  2. {  
  3.    Form2 frm=new Form2(textBox1.Text);  
  4.    frm.Show();  
  5. }  
Conclusion

In this article I discussed the first method and in the next I will explain the other methods.

Up Next
    Ebook Download
    View all
    Learn
    View all