Click here to Skip to main content
Click here to Skip to main content

Passing Data between Windows Forms

By , 27 Jan 2007
 

Introduction

This article provides a simple example of using delegates and events to transfer data between Windows forms. The example provided contains three separate forms; the main form interacts with the other two forms by responding to events generated by instances of the other two forms.

In order to communicate between the forms, each of forms capable of generating an event contains declarations for a delegate and an event. A delegate may be thought of as a type safe function pointer and delegates are associated with methods that bear the same signature. An event is a device used to notify listening objects that something has happened; events are associated with a delegate when instantiated.

Through the use of delegates and events it is possible to communicate values between forms in a Win Forms application.

Figure 1. Using Delegates and Events to Communicate Between Forms

Getting Started.

There is a single solution included with this download, the solution contains a Win Forms project called “PassBetweenForms”; this project contains three forms, one main form that creates instances of the other two forms and responds to events raised by the instances of those two forms.

For the sake of an example, the main form (frmMain) contains an area used to contain an identity (first, middle, and last name) and an area used to display an address (street, city, state, and zip code). The values for these areas are displayed on the form but the form does not allow the user to enter the text directly into the form.

In order to set the values associated with the ID or Address sections of the main form, the user must click on a “Set” button which creates an instance of either the “frmID” form or the “frmAddress” form. When data is entered into and submitted from either of these forms, the main form listens for an update event and then loads the information from either of the other two forms into the main form’s associated text boxes.

Figure 2. Solution Explorer

Code: The Address Form

Rather than starting with the main form, first take a look at the Address form. The Address form contains three parts that make communication with the main form possible. Those parts are the delegate and event declarations and the declaration of a class used to define the content of the event arguments made available to the event listener when the event is fired.

The class declaration contains only the default imports and after the imports, the delegate and event are declared:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PassBetweenForms
{
    public partial class frmAddress : Form
    {
        // add a delegate
        public delegate void AddressUpdateHandler(
            object sender, AddressUpdateEventArgs e);

        // add an event of the delegate type
        public event AddressUpdateHandler AddressUpdated;

        public frmAddress()
        {
            InitializeComponent();
        }
    }
}

The signature of the delegate is pretty standard in this example, it contains the sender as an object and the event arguments; it is possible to use different signatures and return types, the approach used here is just a convenient way to return several values when an event is raised. The “AddressUpdateEventArgs” is the class used to provide a customized argument list to the project. This class inherits from the “EventArgs” class and contains properties used to capture the values provided on the form and to make them available to the listener when the event is fired.

The next bit of code in this class is used to handle the OK button’s click event. When the OK button is clicked from this form, all of the text box values contained in the form are passed to string variables. Once the value have been collected, the custom event argument class is instantiated and, through its constructor, passed each of the values captured from the form. The address updated event is then fired and the event arguments are passed on to the listeners with the event; once the event is raised, the form is closed by calling the dispose method:

       
private void btnOkay_Click(object sender, EventArgs e)
{
    // this button click event handler will raise the 
    // event which can then intercepted by any listeners

    // read the textboxes and set the member
    // variables
           
    string sNewStreet = txtStreet.Text;
    string sNewCity = txtCity.Text;
    string sNewState = txtState.Text;
    string sNewZipCode = txtZipCode.Text;
           
    // instance the event args and pass it each value

    AddressUpdateEventArgs args = 
        newAddressUpdateEventArgs(sNewStreet,  
        sNewCity, sNewState, sNewZipCode);
           
    // raise the event with the updated arguments

    AddressUpdated(this, args);
           
    this.Dispose();
}

The second class contained in the code file is the “AddressUpdateEventArgs” class. This class is pretty straight forward; it contains a set of local member variables used to capture the address information collected from the form and some public read only properties used to access those values. The class constructor accepts all of the arguments necessary to populate the event argument properties. The code is as follows:

public class AddressUpdateEventArgs : System.EventArgs
{
    // add local member variables to hold text
    private string mStreet;

        private string mCity;
        private string mState;
        private string mZipCode;

        // class constructor
        public AddressUpdateEventArgs(string sStreet, 
                string sCity, string sState, 
                string sZip)
        {
            this.mStreet = sStreet;
            this.mCity = sCity;
            this.mState = sState;
            this.mZipCode = sZip;
        }

        // Properties - Viewable by each listener
        public string Street
        {
            get
            {
                return mStreet;
            }
        }

        public string City
        {
            get
            {
                return mCity;
            }
        }

        public string State
        {
            get
            {
                return mState;
            }
        }

        public string ZipCode
        {
            get
            {
                return mZipCode;
            }
        }
}

Code: The ID Form

I am not going to describe the ID form as it is essentially the same as the Address form with the only exception being that it is used to capture the ID related information instead of the address information. The code for the ID form 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 PassBetweenForms
{
    public partial class frmID : Form
    {
        // add a delegate

        public delegate void IdentityUpdateHandler(
                object sender, IdentityUpdateEventArgs e);

        // add an event of the delegate type
        public event IdentityUpdateHandler IdentityUpdated;

        // default constructor
        public frmID()
        {
            InitializeComponent();
        }

        // close the form without raising the event
        private void btnCancel_Click(object sender, 
                                     EventArgs e)
        {
            this.Dispose();
        }

        // raise the event
        private void btnOkay_Click(object sender, 
                                   EventArgs e)
        {
            // this button click event handler will raise
            // the event which can then intercepted by any
            // listeners
            // read the textboxes and set the variables
           
            string sNewFirst = txtFirstName.Text;
            string sNewMiddle = txtMiddleName.Text;
            string sNewLast = txtLastName.Text;
           
            // instance the event args and pass it each
            // value

            IdentityUpdateEventArgs args = 
                newIdentityUpdateEventArgs(sNewFirst,
                sNewMiddle, sNewLast);
           
            // raise the event with the updated arguments
           
            IdentityUpdated(this, args);
            this.Dispose();
        }
    }

    public class IdentityUpdateEventArgs : System.EventArgs
    {
        // add local member variable to hold text
        private string mFirstName;
        private string mMiddleName;
        private string mLastName;

        // class constructor

        public IdentityUpdateEventArgs(string sFirstName, 
            string sMiddleName, string sLastName)
        {
            this.mFirstName = sFirstName;
            this.mMiddleName = sMiddleName;
            this.mLastName = sLastName;
        }

        // Properties - Accessible by the listener
        public string FirstName
        {
            get
            {
                return mFirstName;
            }
        }

        public string MiddleName
        {
            get
            {
                return mMiddleName;
            }
        }

        public string LastName
        {
            get
            {
                return mLastName;
            }
        }
    }
}

Code: Main Form.

The main form of the application is used to display the information originating from the ID and Address forms. The form contains a set of ID and a set of Address related text boxes that cannot be edited directly from the form. The form contains two buttons used to open an instance of either the Address or ID forms; information entered into those two forms is made available to the main form when the update event is fired from either of those forms.

The class is initialized with all of the default settings in terms of class library imports; the first part of the code 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 PassBetweenForms
{
    public partial class frmMain : Form
    {
        // default constructor
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, 
                                  EventArgs e)
        {
            // nothing to do
        }
    }
}        

The first interesting bit of code in the main form is the button click event handler used to respond to a request to set the identity information; that code is as follows:

      
private void btnSetName_Click(object sender, EventArgs e)
{
    frmID f = newfrmID();
           
    // Add an event handler to update this form
    // when the ID form is updated (when
    // IdentityUpdated fires).

    f.IdentityUpdated += new frmID.IdentityUpdateHandler(
                                IdForm_ButtonClicked);
           
    f.Show();
}

In this bit of code, a new instance of the ID form is created. Next, the event used to notify the listener that the ID information has been updated is associated with event handler contained in this, the main form class. After this association is defined, the form is displayed.

The main form event handler associated with the ID form event is as follows:

// handles the event from frmId
private void IdForm_ButtonClicked(object sender, 
                IdentityUpdateEventArgs e)
{
    // update the forms values from the event args
    txtFirstName.Text = e.FirstName;
    txtMiddleName.Text = e.MiddleName;
    txtLastName.Text = e.LastName;
}

This handler accepts the custom event argument list passed when the event is raised and the values contained in the event arguments are used to update the form’s fields in response the event.

The next blocks of code are used to perform the same functions as the last two handlers only for the address information instead of the ID information:

       
private void btnSetAddress_Click(object
                                 sender, EventArgs e)
{
    frmAddress f = newfrmAddress();

    // Add an event handler to update this form
    // when the Address form is updated (when 
    // AddressUpdated fires).
    
    f.AddressUpdated += new frmAddress
        .AddressUpdateHandler(AddressForm_ButtonClicked);
           
    f.Show();
}

// handles the event from frmAddress
private void AddressForm_ButtonClicked(object sender, 
                            AddressUpdateEventArgs e)
{
    // update the forms values from the event args
    txtStreet.Text = e.Street;
    txtCity.Text = e.City;
    txtState.Text = e.State;
    txtZipCode.Text = e.ZipCode;
}

The last bit of code is merely a click event handler for the exit button:

       
private void btnExit_Click(object sender, EventArgs e)
{
    Application.Exit();
}

That concludes the description of all of the code used in this example.

Summary.

The article shows one approach to using events and delegates to pass data between forms through the use of custom event arguments. There are other ways to perform the same tasks but this is a convenient and easy approach to use. Delegates may be defined with different signatures and return types and for that reason is it possible to devise a number of alternative approaches to passing data between forms.

This example showed how the approach can be used to pass multiple values between forms simultaneously, however, one could use the same approach to pass a single value or values of different types just as easily.

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

salysle
Software Developer (Senior)
United States United States
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberterrybozzio26-May-13 6:42 
A very productive way of passing data between forms.
Very good examples.
GeneralMy vote of 5memberbestdealex16-May-13 1:51 
A very good and clear example of how to use the combination of delegate's and event's.
Thank you for the great article!
QuestionHigh 5memberGreatBigYetti22-Mar-13 9:21 
Finally a great example of using delegates and events between forms. Thanks a ton.
GeneralMy vote of 5memberm0nst3r.nva27-Nov-12 16:21 
kool. many thx for this
QuestionCode To Pass Value From One Windows Form To Another Windows Form In Windows Form Using C#memberMember 382310120-Oct-12 5:23 
Hi this is really nice article. Thanks
 
http://dotnetpools.com/Article/ArticleDetiail/?articleId=47&title=Code%20To%20Pass%20Value%20From%20One%20Windows%20Form%20To%20Another%20Windows%20%20Form%20In%20Windows%20Form%20Using%20C#[^]
GeneralMy vote of 5memberAmit.Bhargab18-Aug-12 21:12 
Well, I was looking for something similar. This got my problem solved and I'm happy with the author of this post. Thanks salysle!
Questionre creating instances of Secondary Forms in private methods of a Main FormmemberBillWoodruff29-Jul-12 18:57 
By creating the secondary forms in private methods of the Main Form: you are creating the secondary forms each time the Main Form's private methods are called that create the new secondary Form, subscribe to the update event, etc.
 
Those secondary forms will persist ! That means that, unless you disable the whatever on the Main Form that calls the Main Form methods that create these secondary forms, after the first time they are created: you could end up with more than one of them.
 
Or, you'd have to check for the secondary form already existing, and dispose of it, before re-creating it (an obvious waste of time).
 
In my opinion this is a serious mistake: the secondary forms should be created only once, perhaps in the Load Event of the Main Form, then have their update Events subscribed to: and then Hide them until they need to be shown.
 
Before voting on this article, I'd like to read your response.
 
best, Bill
"Everything we call real is made of things that cannot be regarded as real." Niels Bohr

GeneralI really like this postmembershalabh gupta20-Mar-12 7:46 
Hi Salysle,
 
From so long I was trying to get a hands-on code wherein I can implement this pattern of events and delegates, where notification and subscription of events happen at different places.
 
Via your article I am able to understand this concept properly and also understood how it helps in passing data.
 
I would really appreciate your article and would like to request you if you could provide similar articles on advanced events/delegates concepts/patterns to me.
 
Thanks a lot.
 
Best Regards,
Shalabh
SuggestionThe easier way to do thatmemberMax141419-Mar-12 5:56 
Hi! Great article, which shows "magic of events and delegates".
 
But I have an alternative way to do that and I think it's much simpler and takes less lines & time.
 
So let's assume that we've got MainForm, where is one button, one textbox and on SetForm there is only one button, which will set some text in textBox1 of MainForm and then will close the Form.
 
Firstly set modifier of textBox1 on MainForm to "Internal" (in textBox properties), this causes that the textBox is visible from other files in project.
 
After that, add Click event to button on MainForm:
 
private void button1_Click(object sender, EventArgs e)
{
    AddForm addForm = new AddForm();
    addForm.Show(this);
}
 
Source of AddForm:
 
public partial class AddForm : Form
{
    private MainForm mainForm;
 
    public AddForm()
    {
        InitializeComponent();
    }
 
    private void AddForm_Shown(object sender, EventArgs e)
    {
        mainForm = (MainForm)this.Owner;
    }
 
    private void button1_Click(object sender, EventArgs e)
    {
        MainForm.textBox1.Text = "blabla";
        this.Close();
    }
}
 

So as you see, you can get access by "mainForm" to any control you like, just remember about Modifier. Big Grin | :-D
GeneralIt is perhaps a wrong way!memberAmit.Bhargab18-Aug-12 21:27 
Well, you might have found a short cut for the above solution, but this won't just give access to the code you want, but also to every thing that is within the project having access to this!
Like finding the form and editing as you like:
foreach(Form f in Application.OpenForms)
{
 if(?)//condition for the form
 {
  f.**;//Do whatever  you like!!
 }
}

GeneralMy vote of 5memberGANESH289014-Mar-12 20:29 
Its excellent, i understand how an event is raised, and how i could be handled. thanks for the excellent article.
GeneralMy vote of 5memberprovn20-Feb-12 11:36 
The approach is great!
Thank you!Smile | :) )
GeneralMy vote of 5memberza.amit10-Apr-11 22:59 
Excellent article.
GeneralI got problem when I implemented it to my projectmemberimpauls23-Aug-10 21:43 
private void Updater(object sender, AddressUpdateEventArgs e)
 
It says "The type or namespace name 'AddressUpdateEventArgs' could not be found"
GeneralRe: I got problem when I implemented it to my projectmemberimpauls23-Aug-10 21:45 
by the way...
 
original code was
 
private void AddressForm_ButtonClicked(object sender, AddressUpdateEventArgs e)
{
///some codes
}
 
of mainform... thanks in advance...
Generalwhile implementing the same in managed c++, everything went fine except ... [modified]membercooolguy_0095-Mar-10 22:27 
Error(explained below) occurred while using the managed c++ equivalent of below quoted subscription statement in main form:
"f.IdentityUpdated += new frmID.IdentityUpdateHandler(
IdForm_ButtonClicked);"
Error was "delegate and function signatures do not match".
 
However, when I passed 'this' as additional argument (similar to what is mentioned below),
f.IdentityUpdated += new frmID.IdentityUpdateHandler(
this,
IdForm_ButtonClicked);
in my managed c++ counterpart code, the program ran smoothly.
 
Why was it necessary to add Object^ argument ?
modified on Saturday, March 6, 2010 4:37 AM

GeneralRe: while implementing the same in managed c++, everything went fine except ... [modified]memberPhilippe Mori22-Jan-13 12:53 
Because in C++ you have to be explicit while it is implicit in C#.
Philippe Mori

GeneralExcelent!!memberRICARDO MARCONE7-Feb-10 4:28 
Muito bom o artigo,
parabéns!!
GeneralExcelent!!memberRICARDO MARCONE7-Feb-10 4:28 
Muito bom o artigo, parabéns!!
Generalis there a way to do the same using visual C++memberShaindiarianeioan3-Mar-09 4:17 
is there a way to do the same using visual C++
QuestionGreat solution. Is there any other way to do this?memberBino B15-Nov-08 21:28 
That was a great solution. But im quite confused if we have only this way of passing value between forms. Earlier in VB6 and now in VS 2008 we can create an object of one form in another form and directly access the controls. Is there any way of doing it like i this??
pls mail me @ binobose@gmail.com
 
Cheers
Bino
www.codepal.co.in

AnswerRe: Great solution. Is there any other way to do this?memberpierrecor15-Jan-09 19:50 
I have posted an article how to pass data from a MDI parent form to a child form by passing the MDI parent object. This will expose all the public properties and methods in the parent form. Then once the child is open, you can send any text message to the parent or invoke any public methed in the parent form. I make use of an overriding constructor in the child.
 
The code in the MDI OpenChild_Click event to open a child form and pass the MDI form object to the child form.
            ChildOne child = new ChildOne(this);
 
            child.MessageFromParent = mnuMessageText.Text;
            child.MdiParent = this;
            child.Show();
 
The constructor and Load event in the child form:
   
        public ChildOne()
        {
            InitializeComponent();
        }
 
        //override constructor with the parent form as a parameter
        public ChildOne(MDI m1_)
        {
            InitializeComponent();
            this.mdiParent = m1_;
        }
 
        //call the method to display the value send by the 
        //parent form to the child's property
        private void ChildOne_Load(object sender, EventArgs e)
        {
            DisplayMessageFromParent(); //message from MDI parent

        }
 
This Click event pass data back to the MDI parent into a public property and call a method in the MDI parent to update a text box in the MDI parent.
   
        private void btnPassMessageToParent_Click(object sender, EventArgs e)
        {
            this.mdiParent.ChildMessage = txtMessageToParent.Text;
            this.mdiParent.UpdateMessage();
        }
 
I hope this will help.
 
the confused are confused beyond confusion

AnswerRe: Great solution. Is there any other way to do this?memberThesisus6-Sep-09 9:12 
Actually there are several ways and each has it's own limitations so it depends on your app. I generally find myself however simply creating a class which contains a static variable. Then in form A there is generally an event which creates form B. Form B opens and the the variable mentioned a second ago is assigned a value and the form maybe closed now. Back in form A I'll manage the static variable either by showing it or managing it.
 
Form A
FormB b = new FormB();
b.Show();
textBox.Text = Example.Variable;
 
Form B
Example.Variable = "It's easier than you think.";
 
Example Class
private string _variable = String.Empty;
public static string Variable
{
    get { return _variable; }
    set { _variable = value; }
}

 
Fear not my insanity, fear the mind it protects.

GeneralThat was a great solution!!!memberAnu78714-Oct-08 19:30 
Thanks for ur idea...it really worked 4 me...
Thanks a lot Smile | :)
GeneralPassing Data between Windows formsmemberbullcode13-Oct-08 6:50 
Hi,
I am developing an application.But I am stuck up in passing Data from one Windows form to another.Here is the description :
 
I have Form1.This is the main form.Another Form Form2.Now Form1 has a text box and a button "Button1".Now that I wanted the text entered in textbox of Form1 to appear in Form2 once the "Button1" in Form1 is clicked.Can any one helpe me how to do this.The solution should also be able to work when we have multiple text boxes in both the forms.
 
Cheers
Ravi
GeneralRe: Passing Data between Windows formsgroupHashPe13-May-10 4:05 
when I started to create my first application I used a static class... and used its fields as global variables...
GeneralYou give me another way to solve this problemmemberlightning58310-Sep-08 5:56 
Thank you for writing this and also thanks for sharing your idea.
Before this article, I used to override the constructor with parameters. When create the instance of the form, i pass the variables by using the new constructor, and I think it really works fine. But I now learn a new way to solve this problem, thanks.
GeneralTemperory Streamsmemberammar_shaker16-Apr-08 6:42 
I would use StreamWriter and StreamReader and a temperory .txt file rather than getting lost between classes. Sleepy | :zzz:
GeneralChild from ChildmemberIce_LS0015-Apr-08 0:55 
Hi. You have wrote a very good article. Smile | :)
But i have a question. Imagine That your frmMain calls frmID (just like it does). Then in frmID you call a new form (let's call it frmInsert). In the new frmInsert you want to update the textboxes from frmMain. I have this cenario ( Main - Child1 - Child2 and Child2 wants to update something in Main). How could you do this?
Thanks in advance and again congratulations on a great article.
GeneralI must be a lost cause...memberjoshua4510-Apr-08 3:10 
Some background on my development... I've been strictly web and I do OOP/MVC type programming with ColdFusion/PHP and I've worked with ASP vbscript...
 
Maybe I'm overthinking this but it doesn't make much sense to me... I guess I just figured it would be easier to accomplish this type of task.
 
I have a Course Manager app I'm working on for my department and when creating a Course there is an attendees tab and I want them to be able to add an Attendee by clicking a button.
 
Our database has a Person Table which I'm adding a PersonType table in so that we can assign a Person Type to the person called Attendee. Well I want the Add Attendee button to open a "Person Check" form but also pass in the PersonTypeID of Attendee and the CourseSectionID of the course so it goes through the process of checking if the person exists already, and if so it adds them to the course. If they do not exist it passes that information on to the Person Creation form and after it saves it also adds them to the Course as an attendee.
 
With web I could do this with session variables or query strings. I'm very new to this(like 1 week) so I have no background or knowledge.
 
I guess I could just really use some basics but everything I've read really hasn't applied to what I'm doing so it's been hard to translate.
 
Any help is appreciated! Thanks so much! Wink | ;)
QuestionGreat Article!! I have a question... [modified]memberBadboy22TR19-Feb-08 10:48 
Great Article...Can you translate in Visual C++ ? I tried but i failed Frown | :(
 
modified on Wednesday, February 20, 2008 12:33 AM

GeneralOne of the best article I saw in my lifememberbigshervin27-Nov-07 7:01 
I got sucked how to change text of a simple lable in main form, from two parallel classes.WTF | :WTF: After I read a lot of articles about deligate. OMG | :OMG: I found nothing usefull in real life!Confused | :confused: You saved my life,Smile | :) even you gave me second life to feel this feeling before I die!Roll eyes | :rolleyes: thanks from my second life class to you!Cool | :cool:
GeneralRe: One of the best article I saw in my lifememberAllenR18-Feb-08 3:07 
This is a really simple example. It works for me as is. Smile | :) Smile | :)
 
Thanks,
Allen.
GeneralEssentially good article - but significant bug!memberPete Appleton29-Jan-07 22:42 
Thanks for the article, which I can see being useful for people. There is, however, a significant bug in the code which could have nasty repercussions. In this section
 
IdentityUpdateEventArgs args =
newIdentityUpdateEventArgs(sNewFirst,
sNewMiddle, sNewLast);

// raise the event with the updated arguments

IdentityUpdated(this, args);

there isn't a check to make sure that a delegate is attached to the event. Although that won't happen in this sample, it often does in "real life", and this code will crash with a null reference exception; you need to check that IdentityUpdated isn't null before invoking it.
 
The normal pattern for implementing this pattern would be to have code like the following, which also permits a derived class [form] to override the event trigger and thereby react to the event without the overhead of a delegate - this is the pattern used by the System.Windows.Forms.Control hierarchy itself:

IdentityUpdateEventArgs args =
newIdentityUpdateEventArgs(sNewFirst,
sNewMiddle, sNewLast);

// raise the event with the updated arguments

this.OnIdentityUpdated(args);
}
 
// Raise the IdentityUpdated event
protected virtual void OnIdentityUpdated( IdentityUpdateEventArgs e )
{
if( IdentityUpdated != null ) // Make sure we've got a delegate to invoke
{
IdentityUpdated( this, e );
}
}

Another point (though not a bug per se) is that in .NET v2 there's a generic EventHandler; this means that you don't need to define a specific delegate, but can just use the generic:
 

public event EventHandler IdentityUpdated;


 
--
What's a signature?

GeneralRe: Essentially good article - but significant bug!memberklient8512-Feb-07 23:22 
Pete Appleton wrote:
Another point (though not a bug per se) is that in .NET v2 there's a generic EventHandler; this means that you don't need to define a specific delegate, but can just use the generic:
 

public event EventHandler IdentityUpdated;

 
All events based on delegates, i dont know how to realize that without a delegate. But you can disabuse myself and post a sample. I'm curious about it.
GeneralRe: Essentially good article - but significant bug!memberPete Appleton16-Feb-07 0:24 
It's very easy, actually. The thing is that we have generic event handlers; all you need to code is your EventArgs derivative, and let .NET handle the delegate for you:
public class MyEventArgs : EventArgs { ... }
 
public class SomeClass
{
    public event EventHandler<MyEventArgs> SomethingHappened;
 
    private void SomeFunctionThatRaisesAnEvent()
    {
        MyEventArgs args = new MyEventArgs();
        OnMyEvent( args );
    }
 
    protected virtual void OnMyEvent( MyEventArgs e )
    {
        if( SomethingHappened != null )
        {
            SomethingHappened( this, e );
        }
    }
}

 
--
What's a signature?

GeneralRe: Essentially good article - but significant bug!memberPaul Hatcher15-Feb-07 23:50 
Actually, there's a bug in your bug report - the delegate can become null between the test and invocation, so the thread-safe way to do this is

// Raise the IdentityUpdated event
protected virtual void OnIdentityUpdated( IdentityUpdateEventArgs e )
{
IdentityUpdatedHandler handler = IdentityUpdated;
if( handler != null ) // Make sure we've got a delegate to invoke
{
handler( this, e );
}
}

 
Paul

GeneralRe: Essentially good article - but significant bug!memberPete Appleton16-Feb-07 0:14 
Quite true if this were being used in a multi threaded context; however, a form isn't thread safe to begin with!!! If thread safety were required, then yes, I fully agree with your modification but you'd also have to modify just about everything else about the application to work.
 
I don't disagree with your thread-safety modification; I do disagree with the epithet of "bug" for sample code that conforms to the MSDN usage documentation.
 
MSDN quote: Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
 
--
What's a signature?

GeneralRe: Essentially good article - but significant bug!memberPaul Hatcher16-Feb-07 3:09 
Yeah, you're right about the form's stuff - I just copied it from my standard class event handling logic
 
Paul
 
Paul

QuestionWhat is the best way to set the current values (frmMain) to frmAddressmemberFredyAlfredo29-Jan-07 4:06 
Pass the values in parameters ?
 
frmID f = new frmID(firstName, middleName, lastName);
f.Show();
 

or
 
Create a new delegate & event in MainForm windows for each dialog box option ?
 
Good Article
 


AnswerRe: What is the best way to set the current values (frmMain) to frmAddressmemberDave Herron29-Jan-07 9:01 
Or public / internal methods or controls exposed on the form.
AnswerRe: What is the best way to set the current values (frmMain) to frmAddressmembersalysle29-Jan-07 13:34 
Thanks for comments.
 
Whether or not you can manage the values in a constructor (and pass them as arguments to a form object when it is created) depends on what you are doing. If you are passing some data to the form when it is created, then it is possible to pass the values as arguments to the form.
 
In this example, you are using two forms acting as dialogs to collect information from the user and send that back the main form. Since the main form already exists and since you don't know the values that will be collected using the dialogs, it is not possible to manage the values in the constructor. In a case like that, you can use the approach shown to pass the values back to the main form.
 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 28 Jan 2007
Article Copyright 2007 by salysle
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid