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.
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.
- With constructor
- With objects
- With properties
- 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.
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.
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.
- public Form2(string strTextBox)
- {
- InitializeComponent();
- label1.Text=strTextBox;
- }
Step 2
Use the following code in Form1's Button Handler for Form2.
- private void button1_Click(object sender, System.EventArgs e)
- {
- Form2 frm=new Form2(textBox1.Text);
- frm.Show();
- }
ConclusionIn this article I discussed the first method and in the next I will explain the other methods.