Click here to Skip to main content
Email Password   helpLost your password?

Sample Image - PassData.jpg

Passing Data Between Forms

Introduction

Some of you would have faced a scenario where you wanted to pass data from one form to another in WinForms. Honestly, I too had a similar problem (that’s why I am writing this article!).

There are so many methods (How many? I don't know) to pass data between forms in Windows application. In this article, let me take four important (easiest) ways of accomplishing this:

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

Let us see all the above methods in detail in the following sections.

For data to be passed between forms using any of the above methods, we need two forms and some controls. Let us start by following the steps given below.

Step 1

Create a new project and select Windows application. This will create a default form as “Form1”. We can use this form for sending data.

Step 2

Add a textbox and a button to the form.

Step 3

Add another Windows Form for receiving the data and to display it. Right click the project and select Add->Add Windows Form. Enter a name or use the default name “Form2.cs” and click ok button.

Step 4

Add a label to the second form to display the text from form1.

The Constructor Approach

This could be the easiest method of all. A method is invoked whenever you instantiate an object. This method is called a constructor. Code a constructor for form2 class with one string parameter. In the constructor, assign the text to the label’s text property. Instantiate form2 class in form1’s button click event handler using the constructor with one string parameter and pass the textbox’s text to the constructor.

Follow the steps given below:

Step 1

Code a constructor for form2 class as below:

public Form2(string strTextBox)
{
  InitializeComponent(); 
  label1.Text=strTextBox;
}

Step 2

Instantiate form2 class in form1’s button click event handler as below:

private void button1_Click(object sender, System.EventArgs e)
{
    Form2 frm=new Form2(textBox1.Text);
    frm.Show();
}

The Object Approach

Objects are reference types, and are created on the heap, using the keyword new. Here we are going to pass data using objects. The approach is simple; in form2 we are going to instantiate form1 class.

Then instantiate form2 in the button click event handler of form1. After this we are going to pass form1 object to the form2 using form2’s form1 object. The last step is to invoke the form2 window by calling the form2’s show method.

Follow the below steps:

Step 1

Change the access modifier for textbox in form1 to public:

public class Form1 : System.Windows.Forms.Form
{  
 public System.Windows.Forms.TextBox textBox1;

Step 2

In the button click event-handler, add the following code:

private void btnSend_Click(object sender, System.EventArgs e)
{
    Form2 frm= new Form2();
    frm.frm1=this;
    frm.Show();
}

Step 3

In form2.cs, instantiate form1 class:

public class Form2 : System.Windows.Forms.Form
{
     private System.Windows.Forms.Label label1;
     public Form1 frm1;

Step 4

In Form2’s Load method, type cast the object (frm1) of form1 to Form1 and access form1’s textbox and assign its text to label’s text.

private void Form2_Load(object sender, System.EventArgs e)
{
    label1.Text=((Form1)frm1).textBox1.Text;
}

The Properties Approach

Properties allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method. In this method, we are going to add one property to each form. In form1 we are going to use one property for retrieving value from the textbox and in form2, one property to set the label’s text property. Then, in form1’s button click event handler, we are going to instantiate form2 and use the form2’s property to set the label’s text.

Follow the below steps:

Step 1

Add a property in form1 to retrieve value from textbox:

public string _textBox1
{
    get{return textBox1.Text;}
}

Step 2

Add a property in form2 to set the labels’ text:

public string _textBox
{
   set{label1.Text=value;}
}

Step 3

In form1’s button click event handler, add the following code:

private void button1_Click(object sender, System.EventArgs e)
{
     Form2 frm=new Form2();
     frm._textBox=_textBox1;
     frm.Show();
}

The Delegates Approach

Technically, a delegate is a reference type used to encapsulate a method with a specific signature and return type. You can encapsulate any matching method in that delegate. Here we are going to create a delegate with some signature and assign a function to the delegate to assign the text from textbox to label.

Follow the below steps:

Step 1

Add a delegate signature to form1 as below:

public delegate void delPassData(TextBox text);

Step 2

In form1’s button click event handler, instantiate form2 class and delegate. Assign a function in form2 to the delegate and call the delegate as below:

private void btnSend_Click(object sender, System.EventArgs e)
{
    Form2 frm= new Form2();
    delPassData del=new delPassData(frm.funData);
    del(this.textBox1);
    frm.Show();
}

Step 3

In form2, add a function to which the delegate should point to. This function will assign textbox’s text to the label:

public void funData(TextBox txtForm1)
{
    label1.Text = txtForm1.Text;
}

Conclusion

These four approaches are very simple in implementing data passing between forms. There are also other methods available in accomplishing the same. Source code for the methods I stated above is given at the top for download. It is time for you to put on your thinking cap and find other ways of doing this. Happy coding!!!

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralAbout Multiple Forms in This Project
avisal
7:50 18 Feb '10  
Hello Thiagarajan Alagarsamy

This is nice example,but I do not like opening new form after each click.

To prevent it I modified your codes for delegate example

private void btnSend_Click(object sender, System.EventArgs e)
{
if (pform != null)
{
del(this.textBox1);
}
else
{
// Form2 frm= new Form2();
pform =new Form2();
del = new delPassData(pform.funData);
del(this.textBox1);
pform.Show();
}
}
Where pform and del are global members of Form1

This allow me to send different data to the same form

Regards
Boris
GeneralThanks ..
raindeepak4u
17:39 30 Nov '09  
Thanks for the article Thiagarajan.
Questionsend variable "counter" from form2 to form1 without creating new form!
Member 4070641
12:17 4 Jun '09  
Dear Thiagarajan
At first I appreciate your complete article!Thanx so much!
But I still have a problem!
I have two forms.In form2, I do some processing and I obtain some results.suppose a variable called "counter1".
after this I want to close this form and send this variable to form1.And use it there.
But I don't want to create a new form1 or form1. Please help me.
Regards.
Reza
AnswerRe: send variable "counter" from form2 to form1 without creating new form!
m_qaoud20
0:08 24 Aug '09  
good question... all that time they talking about passing data and nobody answer your question..


you have two opened forms and you wanna pass data between the currents forms (from one to another) ? right?
ok that's easy... we have two steps: i'll explain the best way

but one thing we should know first>>> that one of these two forms should be opened opened after the other one.. as no application started with two opened forms..


form1 ...> the previously opened form and in this example it's the form to which to send data


//////add this code in form1

public partial class Form1 : Form
{

public static string str_to_save = "" ; // global static...used to store strings to be passed



Form2 f2 = new Form2();

if (f2.ShowDialog() == DialogResult.OK)
{
this.textbox2.Text = form1.str_to_save;
}

}



/////////////form2 is the one from which to take data.... you add this code in form2
private void btnsave_Click(object sender, EventArgs e)
{

form1.str_to_save = this.textbox1.Text;
this.DialogResult = DialogResult.OK;
this.Close();
}



hope this help you
Generalpassing arrays
srihari_230
0:36 17 Apr '09  
i want to pass arrays from one form to another, how it can be done or is there a diffrent way to pass data.
GeneralRe: passing arrays
Thiagarajan Alagarsamy
0:54 17 Apr '09  
Srihari,

Thanks for visiting my article. You can pass array object in any of the methods that I have explained in this article.

I have used "string" object in my constructor and properties approach. You can pass the array object in the same way.

Let me know if this helps.

Thanks,
Thiagu

Thanks & Regards
Thiagarajan Alagarsamy

GeneralThanks
AbdullahMansor
20:39 4 Jan '09  
thanka alot
this is that i want.
thank you
GeneralNice
veerabagu
20:50 30 Nov '08  
hi thiagu
its very nice Message keep it up
its surely helpfull to all beginners Rose
GeneralWell done
Luigi Cordova
2:22 28 Apr '08  
Easy and well done article. In few seconds I was able to send everything between forms.
Maybe a good enhancement could be in the explanation in which case a solution is better than an other one.
Thank you
Generalor possibly without the button send feature
isammasri
15:51 27 Sep '07  
or can this be done with multiple textbox fields and have it auto populate labels in the second form without the click of a send button.....
GeneralCan this be done with multiple textbox fields in a form
isammasri
15:49 27 Sep '07  
Is there a way to do this with multiple textbox fields and have the data pass from each textbox field into multiple labels on the second form? (with respect to each textbox field having specific data in each field)

GeneralThere is a much easier way of doing this...
ayayalar
12:02 1 Aug '07  
string returnValue = Application.OpenForms["OpenFormName"].Controls["ControlName"].Text
GeneralRe: There is a much easier way of doing this...
tmom
10:13 13 Oct '07  
Check out this post for refreshing dataGridView from a child form

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1502198&SiteID=1[^]

http://www.vainternet.com
GeneralNice one !
silveroxc
4:17 24 May '07  

Thanks a lot...Nice Article and well explained...
I got just what I was looking for ... Smile


GeneralThat was a Nice Work
venkat_india87
2:18 14 Apr '07  
It really helped

Expecting more From you
GeneralLittle Wrong
Mythran
6:46 7 Dec '06  
In step 4 in the Object Approach, you have:

label1.Text=((Form1)frm1).textBox1.Text;

You are casing frm1 to Form1...but frm1 is declared as Form1 already so no casting required.

HTH,
Mythran
GeneralRe: Little Wrong
Thiagarajan Alagarsamy
19:34 7 Dec '06  
Thanks Mythran for pointing out the mistake.
As you said casting is not required because its already declared.

Thanks & Regards
Thiagarajan Alagarsamy

Generalnice article but...
TheCardinal
1:31 1 Nov '06  
Hi your article really helped a lot.

This is OK when dealing with Parent to Child, but how do you pass data from Child to back to its Parent?

Please help Smile
AnswerRe: nice article but...
Thiagarajan Alagarsamy
2:12 2 Nov '06  
Hi TheCardinal,
When passing the data back to the parent use the same approach...
Let me take the "Pass By Object" method. Create a button and textbox in the child form (Form2) and a label in the parent form (Form1). on the button click event of the child form assign the textbox's text property to the parent form's label text.
for E.g.,


private void btnForm2_Click(object sender, System.EventArgs e)
{
frm1.label1.Text=txtForm2.Text;
}

And remember to declare the parent form's label as public since we need to use it from child.

Please let me know if it works....
Happy coding Smile

Thanks & Regards
Thiagarajan Alagarsamy
GeneralRe: nice article but...
TheCardinal
17:03 2 Nov '06  
Hi Thiagarajan

I have tested your approach and it works!Smile THANKS Smile


GeneralNice
morteza57
0:26 19 Jun '06  
Thanks Thiagarajan Alagarsamy

GeneralNice one
Venkat Eswaran
21:45 16 May '06  
Keep posting.... Smile

Venky
GeneralRe: Nice one
Thiagarajan Alagasamy
1:15 17 May '06  
Thanks VenkatSmile

Thanks & Regards
Thiagarajan Alagarsamy
Generalzoiks, yo!
kryzchek
10:23 16 May '06  
This article is a mess!
GeneralRe: zoiks, yo!
Thiagarajan Alagasamy
18:55 16 May '06  
Sorry kryzchek,
This is my first articleSmile . I prepared my article in MS word and copied the whole text and pasted it here without formattingD'Oh! . I didn't preview the article before publishing.
Now I have formatted the text for a clean layout.
Thanks for pointing it down.


Thanks & Regards,
Thiagarajan Alagarsamy


Last Updated 16 May 2006 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010