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

Pass value between forms using events

By , 22 May 2010
 
This comes up so many times in the Forums/Quick Answers I thought it was time for a Tip that I can point people to.
 
Passing a value from a child form to the parent is best achieved using an event. To a noob, creating events, especialy when passing a value, can seem unnecessarily complicated. The code below shows a simple implementation that can be adapted as required.
 
The example is using Forms, but the priciple applies to any object type.
 
All the code is commented, any questions - just ask!
// TextEventArgs.cs
using System;
 
public class TextEventArgs : EventArgs
{
    // Private field exposed by the Text property
    private string text;
 
    public TextEventArgs(string text)
    {
        this.text = text;
    }
 
    // Read only property.
    public string Text
    {
        get { return text; }
    }
}
// Form2.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Form2 : Form
{
    // Our event
    public event EventHandler<TextEventArgs> NewTextChanged;
    /* Private field to hold the value that is passed around.
     * Exposed by the NewText property and passed in the NewTextChanged event. */
    private string newText;
    /* The following line would normally be automatically created
     * in the Form1.Designer.cs file. */
    private TextBox textBox;
    public Form2()
    {
        InitializeComponent();
        /* The following lines would normally be automatically created
         * in the Form2.Designer.cs file. */
        textBox = new TextBox();
        textBox.Location = new Point(92, 122);
        textBox.TextChanged += new EventHandler(textBox_TextChanged);
        Controls.Add(textBox);
    }
    // textBox.TextChanged handler
    private void textBox_TextChanged(object sender, EventArgs e)
    {
        NewText = textBox.Text;
    }
    public string NewText
    {
        get { return newText; }
        /* Setting this property will raise the event if the value is different.
         * As this property has a public getter you can access it and raise the
         * event from any reference to this class. in this example it is set from
         * the textBox.TextChanged handler above. The setter can be marked as
         * as private if required. */
        set
        {
            if (newText != value)
            {
                newText = value;
                OnNewTextChanged(new TextEventArgs(newText));
            }
        }
    }
    // Standard event raising pattern.
    protected virtual void OnNewTextChanged(TextEventArgs e)
    {
        // Create a copy of the event to work with
        EventHandler<TextEventArgs> eh = NewTextChanged;
        /* If there are no subscribers, eh will be null so we need to check
         * to avoid a NullReferenceException. */
        if (eh != null)
            eh(this, e);
    }
}
// Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class Form1 : Form
{
    /* The following line would normally be automatically created
     * in the Form1.Designer.cs file */
    private Button buttonShowForm2;
    public Form1()
    {
        InitializeComponent();
        /* The following lines would normally be automatically created
         * in the Form1.Designer.cs file */
        buttonShowForm2 = new Button();
        buttonShowForm2.Location = new Point(105, 121);
        buttonShowForm2.Text = "Show Form2";
        buttonShowForm2.Click += new EventHandler(buttonShowForm2_Click);
        Controls.Add(buttonShowForm2);
    }
    private void buttonShowForm2_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        // Subscribe to event
        form2.NewTextChanged += new EventHandler<TextEventArgs>(form2_NewTextChanged);
        form2.ShowDialog();
        // Unsubscribe from event
        form2.NewTextChanged -= form2_NewTextChanged;
        form2.Dispose();
        form2 = null;
    }
    // Our new event (form2.NewTextChanged) handler
    private void form2_NewTextChanged(object sender, TextEventArgs e)
    {
        Text = e.Text;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DaveyM69

United Kingdom United Kingdom
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   
Question[My vote of 1] Confused - My vote of Zero.memberchowdary200526-Sep-12 18:23 
Poor presentation. No boday can understand this with out help of source code in a project.
For me this is confuesed. Better if can add the example as a project with source.
AnswerRe: [My vote of 1] Confused - My vote of Zero.mentorDaveyM6929-Sep-12 12:59 
It's not possible to add a project attachment to a tip, only to articles. I have an article on events with plenty of source in a project if you are finding this difficult to follow Wink | ;)
Events Made Simple[^]
 
With 21 out of the other 22 votes (excluding yours) being a 5, and the other being a 4, obviously others have not had a problem following this.
Dave

Binging is like googling, it just feels dirtier.
Please take your VB.NET out of our nice case sensitive forum.
Astonish us. Be exceptional. (Pete O'Hanlon)

BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)



GeneralMy vote of 5memberMarcus Kramer26-Sep-12 4:16 
5.
GeneralReason for my vote of 5 Nice and loosely coupled, my 5!memberjim lahey1-Feb-12 23:34 
Reason for my vote of 5
Nice and loosely coupled, my 5!
GeneralReason for my vote of 5 As one gets into programming models,...memberxzz019511-Aug-10 3:48 
Reason for my vote of 5
As one gets into programming models, the deeper we go, the more events raise their first class status. We become aware of their benefits and wonder why we still insist on Waterfall methodology.
GeneralReason for my vote of 5 Thanks for sharing this tip.memberlinuxjr5-Aug-10 17:26 
Reason for my vote of 5
Thanks for sharing this tip.
GenerallosermemberBarbo1-Sep-10 23:09 
noob
Thumbs Down | :thumbsdown:
GeneralRe: losermemberCarsten V2.01-Oct-12 8:44 
Do you think this is professional?

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 22 May 2010
Article Copyright 2010 by DaveyM69
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid