5,427,303 members and growing! (14,943 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Passing Data Between Forms

By Thiagarajan Alagarsamy

This arcticle is aimed at providing some simple methods for passing data between forms in Windows application
C#, Windows, .NET, Visual Studio, Dev

Posted: 16 May 2006
Updated: 16 May 2006
Views: 52,884
Bookmarked: 21 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
42 votes for this Article.
Popularity: 4.24 Rating: 2.61 out of 5
13 votes, 31.0%
1
3 votes, 7.1%
2
5 votes, 11.9%
3
2 votes, 4.8%
4
19 votes, 45.2%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
Passing Data Between Forms 

Sample Image - PassData.jpg

 

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 a 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 below steps.

 

Step 1: Create 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 below steps.

 

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 your thinking cap and find other ways of doing this. Happy Coding!!!

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Thiagarajan Alagarsamy


Thiagu is living in Bangalore, India. He has started coding when he was 12 years old. His native is Madurai, a historic city in south India. He loves to code in C#. He frequents code project when he is not coding. Thiagu loves reading Dan Brown and Michael Crichton novels. He is very much interested in Artificial Intelligence (AI). To view his blog - http://csharpnet.blogspot.com

Occupation: Web Developer
Location: India India

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 17 of 17 (Total in Forum: 17) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralWell donememberLuigi Cordova2:22 28 Apr '08  
Generalor possibly without the button send featurememberisammasri15:51 27 Sep '07  
GeneralCan this be done with multiple textbox fields in a formmemberisammasri15:49 27 Sep '07  
GeneralThere is a much easier way of doing this...memberayayalar12:02 1 Aug '07  
GeneralRe: There is a much easier way of doing this...membertmom10:13 13 Oct '07  
GeneralNice one !membersilveroxc4:17 24 May '07  
GeneralThat was a Nice Workmembervenkat_india872:18 14 Apr '07  
GeneralLittle WrongmemberMythran6:46 7 Dec '06  
GeneralRe: Little WrongmemberThiagarajan Alagarsamy19:34 7 Dec '06  
Generalnice article but...memberTheCardinal1:31 1 Nov '06  
AnswerRe: nice article but...memberThiagarajan Alagarsamy2:12 2 Nov '06  
GeneralRe: nice article but...memberTheCardinal17:03 2 Nov '06  
GeneralNicemembermorteza570:26 19 Jun '06  
GeneralNice onememberVenkat Eswaran21:45 16 May '06  
GeneralRe: Nice onememberThiagarajan Alagasamy1:15 17 May '06  
Generalzoiks, yo!memberkryzchek10:23 16 May '06  
GeneralRe: zoiks, yo!memberThiagarajan Alagasamy18:55 16 May '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 May 2006
Editor:
Copyright 2006 by Thiagarajan Alagarsamy
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project