How to send value from one form to another using C#.Net



There are so many cases in which programmer have to pass some values from one Form to another, like he/she has a list form and want to edit that record in another form, in that case he/she has to pass a unique key of that record so that record can be processed easily.

Today i will tell you two ways for sending values from one form to another using C#.Net.

1. Send Value using Object.

2.Send Value using Constructor.


In the Previous articles i explained how to insert record into database from listview control using C#.nethow to backup and restore access database using c#.nethow to backup and restore access database using c#.nethow to fill dataset using, how to pick data from dataset using and many more about C#.Net.

1. Send Value using Object.

Step 1.

Add two forms to your solution and name it as "Form1.cs" and "Form2.cs" respectively.

Step 2.

We will send Form1 TextBox value to Form2 Label Control.

So, Add one TextBox and a Button on Form1 and a Label on Form2.

Step 3.

Open From2.Designer.cs File.

Step 4.

Replace this line  "private System.Windows.Forms.Label label1" with "Public System.Windows.Forms.Label label1"

This will make Label1 Public. And we can use it any Form.

Step 5.

Open Form1.cs and Double click on Button.

Step 6.

Write Below code on click event of the button.

Form2 op = new Form2();
op.label1.Text = this.textBox1.Text;

You are Done. Debug you application for checking.

Type anything in a TextBox and after that click on button. You will see Form1 TextBox's Text to Form2 Label Control.


2.Send Value Using Constructor.

Step 1.

Drag and Drop Button on Form1

Step 2.

Drag and Drop Label on Form2.

We will Send value from Form1 to Form2 Label control.

Step 3.

Open Form2.cs Code Behind File. And make a String variable "value" to accept value in a constructor.

Step 4.

Make another string type variable "get_value" to accept value from constructor.

Step 5.

Now pass value of constructor to "get_value" variable. See Below Screenshot.

Step 6.

Pass value retrived from constructor to Label1 Text. Write Following Code on Load of Form2. See Below Screenshot.

Step 7.

Open Form1 and Double Click on button and write the below code on click event of the button.

 Form2 op = new Form2("i am sending value from Form1");

You are Done.

Test Your Application. When you click button you will see the message on Form2 like "i am sending value from Form1". See Below Screenshot.

Hope you learnt two new things Today.

Give your Valuable Comments.
comments powered by Disqus
Follow me on twitter
About Me
Harpreet Singh
I began programming with C++ when i was 17. Then at the middle of my study .NET came. Then I began to read C# and VB.NET. By the time i learnt SQL and ASP.NET, and developed some websites such as news portals that are active now. Currently i am running my own Software company.
More Articles