Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio 2010 » 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:
Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 666
Total page views :  23437
Rating :
 3.67/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
LimitedDataXfer.zip
 
Become a Sponsor



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.


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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
LimitedDataXfer.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
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 | Delete | Modify | 
Re: Visibility of Form1 Controls by Jucinaldo On February 11, 2007
Is true, how to resolv this. thanks...
Reply | Email | Delete | 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 | Delete | Modify | 
Constructor by ojd On February 15, 2007
The code f = new Form1(); should be in the first, paramter less constructor.
Reply | Email | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved