Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Visual C# » Passing Data Between Forms Without Events and Delegates

Passing Data Between Forms Without Events and Delegates

This article describes a simplified approach to allowing communication between forms without the use of events and delegates.

Author Rank :
Page Views : 34602
Downloads : 1037
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
LimitedDataXfer.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

This article describes a simplified approach to allowing communication between forms without the use of events and delegates. The approach demonstrated is adequate if the application uses a single instance of a form and allows the creation of a single instance of a dialog used to pass data to the main calling form. If you need to broadcast the data generated by a dialog to multiple form listeners, you will still need to work with events and delegates; this approach is only valid if there is a one on one relationship between the two interactive forms.



Figure 1.  Data entered in the Right Form immediately appears in the Left Form
 

Getting Started.

There is a single Win Forms application included with this download. You may open the project and examine the files and code if you wish; however, the code is quite simple and will be described in the following sections of this document. All examples were written using Visual Studio 2005 and are in C#; the same code could also be used in earlier versions of Visual Studio.

In general the application contains only two forms. Form 1 opens with the application and it contains five label controls which act as targets for data entered from Form 2. Form 1 is titled, "Originator" and Form 2 is labeled, "Data Entry".  

Code:  Form 1.

Form 1 contains five labels and a button. The five labels carry default text whenever an instance for Form 1 initially created. The labels are set to display "Name", "Street", "City", "State", and "Zip Code". There is also a single button contained on the form. Whenever this button is clicked, a new instance of Form 2 is created. Form 2 has an overloaded constructor and it accepts an object of type Form 1 as an argument. By passing the current Form 1 to instances of Form 2 through the constructor, it is possible to communication directly between the forms without adding events and delegates.

The entire body of code contained in Form 1 is as follows:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace LimitedDataXfer

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btnOpenForm_Click(object sender, EventArgs e)

        {

            Form2 f = new Form2(this);

            f.Show();

        }

    }

}

Looking over the code you will not that nothing but the default imports are included in the definition of the form class. The class definition is also in the default configuration. The only code added to the class is that used to handle the single buttons click event. In that click event handler, a new instance of Form 2 is created and it is pass "this" as an argument. After the current Form 1 is passed to the form 2 constructor as an argument, the Form 2 instance is displayed to the user.

By passing the current Form 1 object to Form 2 in this manner, Form 2 may directly access any property in Form 1 instance to include each of the labels that will be populated through Form 2. This will allow communication between the two forms without the definition an delegates or events used to handle that communication. 

Code:  Form 2.

The code behind Form 2 is also very simple. This form also contains only the default imports and the class declaration is also per the default configuration. The form does contain an overloaded constructor which is configured to accept an object of type Form 1 as an argument. If a Form 1 object is passed to the constructor, a local object of type Form 1 will be set to point to this passed in form.

The entire body of code contained in this class is as follows:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace LimitedDataXfer

{

    public partial class Form2 : Form

    {

        Form1 f;

 

        public Form2()

        {

            InitializeComponent();

        }

 

        public Form2(Form1 fr1)

        {

            InitializeComponent();

            f = new Form1();

            f = fr1;

        }

 

        private void Form2_Load(object sender, EventArgs e)

        {

          

        }

 

        private void textBox1_TextChanged(object sender, EventArgs e)

        {

            f.lblName.Text = textBox1.Text;

        }

 

        private void textBox2_TextChanged(object sender, EventArgs e)

        {

            f.lblStreet.Text = textBox2.Text;

        }

 

        private void textBox3_TextChanged(object sender, EventArgs e)

        {

            f.lblCity.Text = textBox3.Text;

        }

 

        private void textBox4_TextChanged(object sender, EventArgs e)

        {

            f.lblState.Text = textBox4.Text;

        }

 

        private void textBox5_TextChanged(object sender, EventArgs e)

        {

            f.lblZip.Text = textBox5.Text;

        }

    }

}

In the code above, you will note that the overloaded constructor is configured to accept the Form 1 object as an argument and you can see that the local Form 1 object is set to this passed in Form 1 object. The remainder of the code is merely used to handle the text changed event for each of the text boxes contained in the Form 2 object. Whenever the text in any of the text boxes is changed, the current value of that text box is immediately passed to the appropriate label control in the Form 1 object.

When the application is run and the Form 2 object is created, typing into any of the text boxes will immediately update the Form 1 object's applicable label control.   

Summary.

This example demonstrates a simplified approach to transmitting data between forms without any reliance upon delegates and events. Since the approach shown requires passing the calling form as an argument to the new form which in turn will operate on the calling form, the approach is limited to instances where that relationship may be enforced and where communication between the two forms is adequate. If you need to broadcast information to multiple forms, you will need to rely on events and delegates to accomplish the task.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Visibility of Form1 Controls by Jon On February 7, 2007
It is in the sample code but not mentioned in this narrative that you need to change the visibility of the controls in form1 from private to public to make them accessible to form2. This needs to be done in Form1.Designer
Reply | Email | Modify 
Re: Visibility of Form1 Controls by Jucinaldo On February 11, 2007
Is true, how to resolv this. thanks...
Reply | Email | Modify 
Re: Visibility of Form1 Controls by Oscar On April 10, 2007

Avoid to do this, instead of, use properties to modify the controls of the forms. That is the correct way to do that

 

public string LabelName

{

 set { this.lblName = value;}

}

Reply | Email | Modify 
Constructor by ojd On February 15, 2007
The code f = new Form1(); should be in the first, paramter less constructor.
Reply | Email | Modify 
passing data to and from forms by nayana On May 14, 2007
I am having two forms with one checkbox each. When the checkbox of one form is checked it should be reflected in the other form also. But as i am writing code in checkbox_checkchanged and it is contained in both the forms its getting into loop.Can u help me to find a solution for this.
Reply | Email | Modify 
Re: passing data to and from forms by Scott On May 14, 2007
I responded to the other posting you'd made.
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.