Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 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 » C# Language » Using delegates to communication between windows forms

Using delegates to communication between windows forms

Delegates are one of the wonderful features of .Net Framework. Their primary use is focused on support event handling and callback mechanism. In this article we will explore how to use delegate as callback support to make simple communication between deferent opened windows forms

Author Rank:
Technologies: .NET 1.0/1.1, Windows Forms,Visual C# .NET
Total downloads : 1408
Total page views :  42369
Rating :
 4.8/5
This article has been rated :  15 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
DelegatesWinFormsDemo.zip
 
ArticleAd
Become a Sponsor



Introduction:

Delegates are one of the wonderful features of .Net Framework. Their primary use  is focused on support event handling and callback mechanism. In this article we will explore how to use delegate as callback support to make simple communication between deferent opened windows forms.

In this article, I assume that you know the definition of delegate and its primary use in .Net Framework.

Scenario overview:

In many scenarios, a windows form is used to open some other windows forms as modal or non-modal. The newly opened form or the opener itself (the parent form) may need to send each other some notifications or values. For example, you select a value from a ComboBox on the newly opened form, and you want to send this value immediately on select to the opener parent form. Or you changed a parameter value in the opener form (parent) that the newly opened form depends on. Such scenarios can be implemented using delegates in form of callbacks.

Scenario in action:

We are going to explore 2 scenarios:

  • First Scenario: A main windows form (parent) that can open deferent instances of other windows forms (children).

    The parent form will contain a TextBox, when the text in this text box changes, all opened windows forms (children) should be notified with this change an display it.

  • Second Scenario: A main windows form (parent) that contains a ListBox will open a dialog form that contains a TextBox with tow buttons (Add Item) & (Close). Whenever the user click the Add Item button, the item should be added to the ListBox in the main form without closing the dialog. Close button should close the dialog.

Of course these scenarios can be done by exposing controls as public instances. But many would prefer to keep controls as private and start using delegates

The Rule:

First of all, you need to decide what do you want to send to the other form cause this will lead you to decide what is the parameter type you will use in your delegate.

In our case here, we need only to pass string, so we need to define delegate with string as parameter for example:

public delegate void SetParameterValueDelegate(string value);

Second, you need to decide who is the owner of the communication, in other words, which form will send the notification?! In our first scenario the main form (parent) will be the owner of the communication. But in the second scenario the dialog form will be the owner.

Once you decide the owner, you'll need to declare an instance of your delegate type inside the owner class for example:

public SetParameterValueDelegate SetParameterValueCallback;

The other forms will be subscribers for the callback (delegate), only if you wish to send notification to them.

The First Scenario:

The following screenshot shows the first scenario in action, just to note the simple user interface we are using to demonstrate the example:

You need to declare a delegate, should be out side any class for our example needs.

Listing 01-Declare a delegate:

public delegate void SetParameterValueDelegate(string value);

The following is the code written in the Main From "FrmMain Class":

Listing 02-FrmMain Class:

//Declare delagete callback function, the owner of communication
public
SetParameterValueDelegate SetParameterValueCallback;

private void btnOpenFrm1_Click(object sender, EventArgs e)
{

FrmChild1 frm = new FrmChild1();
//Subscribe frm for Callback

this
.SetParameterValueCallback += new SetParameterValueDelegate(frm.SetParamValueCallbackFn);
frm.Show();

}
private
void btnOpenFrm2_Click(object sender, EventArgs e)
{

FrmChild2 frm = new FrmChild2();
//Subscribe frm for Callback

this
.SetParameterValueCallback += new SetParameterValueDelegate(frm.SetParamValueCallbackFn);
frm.Show();

}
private
void txtParam_TextChanged(object sender, EventArgs e)
{

//Send Notification to all subscribers
SetParameterValueCallback(txtParam.Text);

}

Did you note the frm.SetParamValueCallbackFn?! Well this is method defined in both FrmChild1 & FrmChild2 forms, of course the method can have deferent names on each class.

What you should know and note, this method should have the same signature as the delegate, which means, the delegate is void, your method should be void, the delegate accepts only one string parameter, your method also should accept only one string parameter.

The following shows the definition of the SetParamValueCallbackFn method:

Listing 03-SetParamValueCallbackFn Method:

public void SetParamValueCallbackFn(string param)
{

txtParam.Text = param;

}

The Second Scenario:

You might guessed what we should do in this scenario, first we will create a new delegate that takes a string parameter, we will call  it AddItemDelegate. In the Dialog form (FrmDialog) we will declare a callback method of type AddItemDelegate. In main from (FrmMain) we will define the callback function.

Listing 04-AddItemDelegate:

public delegate void AddItemDelegate(string item);

Listing 05-FrmDialog Class:

//Declare delagete callback function, the owner of communication
public AddItemDelegate AddItemCallback;
private void btnAdd_Click(object sender, EventArgs e)
{

//Notification subscribers
AddItemCallback(txtItem.Text);

}

Listing 06-FrmMain Class:

private void btnScenario2_Click(object sender, EventArgs e)
{

FrmDialog dlg = new FrmDialog();
//Subscribe this form for callback

dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn);
dlg.ShowDialog();

}
private
void AddItemCallbackFn(string item)
{

lstBx.Items.Add(item);

}

Conclusion:

The way of using delegates to send information between windows forms is much more clear than exposing controls as public instances, well this is my opinion.

In the examples represented here, we could use on delegate instead of tow, but I represented this just for clarification. Hope you find it useful.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Muhammad Mosa
Muhammad M. Mosa Soliman: Software Engineer, graduated from the Faculty of Computers & Information Systems year 2003-Ain Shams University- in Cairo. Working with Microsoft .NET technology since early beta releases. Main experiance based on ASP.NET, SharePoint Portal 2003 & SQL Server. Worked as trainer for Microsoft .NET for 2 years in Cairo. Likes to read about new technologies and self-learning. Extremly Hard worker when motivated. MCT MCSD.NET MCTS: .Net 2.0 Web/Windows Applications MCPD: Enterprise Application Developer MCTS: WSS 3.0 & MOSS 2007 Config
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.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
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.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
DelegatesWinFormsDemo.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Delegate use in Net 2.0 C#Jim4/3/2007
Muhammad, Nice job explaining the use of delegates. It helped me understand it a lot better. Jim Hoban
Reply | Email | Delete | Modify | 
 
 
Re: Delegate use in Net 2.0 C#Muhammad4/6/2007

Thank you so much for your comment, it really gives me push when I find my doings useful for someone.

Regards,

Reply | Email | Delete | Modify | 
Passing data to and from formsnayana5/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 formsMuhammad5/15/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.

I've simulated this using delegates and it is working just fine, so please try the following:

Declare a delegate to manage communication between the 2 forms, for example:
public delegate void CheckedChanged(bool newValue);

In your both windows forms classes declare an object of the above delegate type:
public CheckedChanged checkedChangedCallback;

Define the methods that will be used by the delegates, you should create a method on each class:

public void CheckedChangedReceived(bool value)
{
   checkBox1.Checked = value;
}

Now every form should subscribe to the correct delegarte:
Form1 should subscribe to the delegate in Form2
Form2 should subscribe to the delegate in Form1
because my sample is working on this article sample here is how I did that:

private void btnOpenFrm1_Click(object sender, EventArgs e)|
{
    FrmChild1 frm = new FrmChild1();
    //Subscribe frm for Callback
   
this.checkedChangedCallback += new  CheckedChange(frm.CheckedChangedReceived);
    frm.checkedChangedCallback +=
new CheckedChanged(this
.CheckedChangedReceived);
frm.Show();
}

Finally on the CheckedChanged Event Handler of each CheckBox
code the following line:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
   checkedChangedCallback(
this.checkBox1.Checked);
}

Hope this would help

Reply | Email | Delete | Modify | 
thanks a lot Santiago6/15/2007
oh almighty muhammad u were the one that really helped me to solve my question about this, and that delegates are really cool, thanks a lot
Reply | Email | Delete | Modify | 
 
 
Re: thanks a lot Muhammad6/16/2007

Santiago, thanks a lot for your comment. I feel great that you find it useful and helpful.

Regards,

Reply | Email | Delete | Modify | 
Delegate use in Net 2.0 C#Madhan6/27/2007
A good job Muhammad. Your article gave a clear idea of implementing delegates
Reply | Email | Delete | Modify | 
 
 
Re: Delegate use in Net 2.0 C#Muhammad6/28/2007
Thanks a lot Madhan, I really appreciate your comment. And happy that you find it helpful
Reply | Email | Delete | Modify | 
updating a textbox from a non-form classiman10/28/2007
Hi! Thanks a lot for the article! Never seen it explained better! My situation is slightly different though... I have a peer to peer application that is built on ICE. I need to change the value of a textbox from a C++ class created within one of the forms's methods. It is not a form though. I want to pass it a pointer to the form so that it might change the value of the textbox but it isnt working. I try to send "this". and ofcourse I get errors such as that I should use ^ instead, etc... Any advice?
Reply | Email | Delete | Modify | 
 
 
Re: updating a textbox from a non-form classDmitriy2/27/2008
Yes! Thanks for your job!
Reply | Email | Delete | Modify | 
Thanks you!kwix10/7/2008
Thank you! This is exactly what i was looking for. Keep posting great articles and real-world examples. :)
Reply | Email | Delete | Modify | 
Thanks you!kwix10/7/2008
Thank you! This is exactly what i was looking for. Keep posting great articles and real-world examples. :)
Reply | Email | Delete | Modify | 
 
 
Re: Thanks you!Ravinda10/27/2008

Thank's for your great work. I need help with one of my projects.

I have a Windows Form for the user to enter data. There is a button  on my Form that call a nother form which gets details from database, based on the use entered value

Example : If the user has entered 123 as CutomerID. When I click the button a new form should apper with order details.

 

Thanks

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