How to pass data between two forms in C#

cgeier 4 Tallied Votes 4K Views Share

I will be showing how to pass data between two forms in C#. I will be using two forms, two classes which we will define, a delegate, an event, and an event handler. It is a bit long because I wanted to make it easy to follow. If you want to skip the explanation and just see the code, scroll down to "The short version:"

  • A form named: MainFrm
  • A form named: ChildFrm
  • A class named: ScheduleInfo
  • A class named: ValueUpdatedEventsArgs

An instance of ChildFrm will be created and shown when clicking a button on the main form (MainFrm). After adding our data in the child form (ChildFrm), we will click a button on the child form to send the data back to the main form. Then on the main form we will display the newly received data, as well as add our data to a list (or update the data in the list if it was previously added).

Let’s start out by creating a new Project (select “Windows Forms Application”). Next, rename “Form1.cs” to “MainFrm.cs”. (Right-click "Form1.cs" in Solution Explorer and choose "Rename". Rename it to "MainFrm.cs". You should be prompted, "You are renaming a file. Would you like to perform a rename in this project of all references....?" Click, "Yes".) Right-click on the form, select “Properties” and change the “Text” property from “Form 1” to “MainFrm".

Now let’s create a new class called "ScheduleInfo.cs". An instance of this class will be used to hold the data that we want to pass between the forms.

  • On the menu bar, click “Project”
  • Select “Add Class”
  • For the name, enter “ScheduleInfo.cs”
  • Click “Add”.

Next, we will modify the code contained within “ScheduleInfo.cs”. I will go over three different options that you can use for “ScheduleInfo.cs”. One option will use public variables. The other two options will use Properties, and show two different ways of using them. For demonstration purposes, “ScheduleInfo” only contains two variables / properties. You can add more if you like.

Replace the code in “ScheduleInfo.cs” so that it looks like the following (leave the “using” statements at the top):

    public class ScheduleInfo
    {

    }

Next, we will add some variables and/or properties to ScheduleInfo. Look over the three options below and choose the one that you would like to use.

Option 1: (public variables)

    public class ScheduleInfo
    {
        public string Name      = string.Empty;
        public string EventType = string.Empty;
    }

Option 2 (Property):

    public class ScheduleInfo
    {
        //Property Name
        public string Name { get; set; }

        //Property EventType
        public string EventType { get; set; }
    }

Option 3 (Property):

    public class ScheduleInfo
    {

        private string _name = string.Empty;
        private string _eventType = string.Empty;

        //Property Name
        public string Name
        {
            get
            {
                return this._name;
            } //get

            set
            {
                this._name = value;
            } //set
        } //Name

        //Property EventType
        public string EventType
        {
            get
            {
                return this._eventType;
            } //get

            set
            {
                this._eventType = value;
            } //set
        } //EventType

    }

Next, we create a new class called "ValueUpdatedEventArgs.cs". An instance of this class will be used to pass the data between the forms.

  • On the menu bar, click “Project”
  • Select “Add Class”
  • For the name, enter “ValueUpdatedEventArgs.cs”
  • Click “Add”

Now, we will modify the code contained within “ValueUpdatedEventArgs.cs”.

Replace the code in “ValueUpdatedEventArgs.cs” so that it looks like the following (leave the “using” statements at the top):

    public class ValueUpdatedEventArgs
    {

    }

We want to inherit from System.EventArgs. We do it like this:

    public class ValueUpdatedEventArgs : System.EventArgs
    {

    }

Next we want to use a delegate to help us transfer our data between forms. See this documentation, for more information about delegates.

Let's add our delegate to "ValueUpdatedEventArgs.cs":

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {

    }

Next, we want to have a place to store our data that we need to pass between forms. We will use an instance of "ScheduleInfo". Once again, we have options of how to do this. I will go over three different options that you can use for “ValueUpdatedEventArgs.cs”. One option will use public variables. The other two options will use Properties, and show two different ways of using them. In all three options, we will use an instance of ScheduleInfo to hold the data. Look over the three options below and choose the one that you would like to use.

Option 1 (using a public variable):

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        public ScheduleInfo Schedule;
    }

We need a way to get our data into our instance of "ValueUpdatedEventArgs", so let's create a constructor:

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        public ScheduleInfo Schedule;


        public ValueUpdatedEventArgs(ScheduleInfo Schedule)
        {
            this.Schedule = Schedule;
        }//constructor
    }

Option 2 (Property):

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        //Property Schedule
        public ScheduleInfo Schedule { get; set; }


    }

We need a way to get our data into our instance of "ValueUpdatedEventArgs", so let's create a constructor:

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        //Property Schedule
        public ScheduleInfo Schedule { get; set; }


        public ValueUpdatedEventArgs(ScheduleInfo Schedule)
        {
            this.Schedule = Schedule;
        }//constructor
    }

Option 3 (Read-only Property):

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        //instance of ScheduleInfo
        private ScheduleInfo _schedule;


        //ReadOnly Property Schedule
        public ScheduleInfo Schedule
        {
            get
            {
                return this._schedule;
            }//get
        }//Schedule

    }

We need a way to get our data into our instance of "ValueUpdatedEventArgs", so let's create a constructor:

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        //instance of ScheduleInfo
        private ScheduleInfo _schedule;


        public ValueUpdatedEventArgs(ScheduleInfo Schedule)
        {
            this._schedule = Schedule;
        }//constructor


        //ReadOnly Property Schedule
        public ScheduleInfo Schedule
        {
            get
            {
                return this._schedule;
            }//get
        }//Schedule

    }

We're finished with ValueUpdatedEventArgs. Next, let's look at the child form (ChildFrm).

  • Create a new "Windows Form" and name it "ChildFrm.cs".
  • In menu bar, click “Project”
  • Select “Add New Item”
  • Select “Windows Form”
  • For the name, enter “ChildFrm.cs”
  • Click “Add.

Add a TextBox (named: nameTextBox), a ComboBox (named: eventTypeComboBox), a label (Text property = “Name:”), a label (Text property = “Event Type:”), and a button (named: addBtn) to the form (ChildFrm). Double-click the button to create a "Click" event handler for the button.

d269ae20b6901421620f899eba6aa249

The code for ChildFrm should look like this:

    public partial class ChildFrm : Form
    {
        public ChildFrm()
        {
            InitializeComponent();
        }

        private void addBtn_Click(object sender, EventArgs e)
        {

        }
    }

We want to create an event (in ChildFrm) that can be raised in ChildFrm that the main form (MainFrm) can listen for (and handle). We do it like this:

public event ValueUpdatedEventHandler ValueUpdated;

Our code will now look like this:

    public partial class ChildFrm : Form
    {
        //event interested parties can register with to know
        //when value is updated.
        //ValueUpdatedEventHandler is delegate defined in 
        //ValueUpdatedEventArgs

        public event ValueUpdatedEventHandler ValueUpdated;

        public ChildFrm()
        {
            InitializeComponent();
        }

        private void addBtn_Click(object sender, EventArgs e)
        {

        }
    }

Let's create an instance of ScheduleInfo to hold our data that we want to pass back to the main form (MainFrm).

    //create new instance of ScheduleInfo
     ScheduleInfo _schedule;

Now, let's create a method that we can use to send our data back to the main form (MainFrm).

       private void SendUpdates(ScheduleInfo Schedule)
        {

        }

Here's what we want to do inside "SendUpdates". First, we’ll check to ensure that “ValueUpdated != null”. Then, we want to declare a new instance of "ValueUpdatedEventArgs" and pass our local copy of ScheduleInfo to the constructor.

if (ValueUpdated != null)
{
    ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(Schedule);

}//if

So now we have:

        private void SendUpdates(ScheduleInfo Schedule)
        {

            if (ValueUpdated != null)
            {
                //create new instance of ValueUpdatedEventArgs
                //passing our local instance of ScheduleInfo
                //to the constructor

                ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(Schedule);

            }//if
        }//SendUpdates

Next, we raise the event:

//raise the event
//valueArgs is an instance of ValueUpdatedEventArgs
//and contains an instance of ScheduleInfo
//which we want to pass to our main form (MainFrm)

ValueUpdated(this, valueArgs);

Here's what "SendUpdates" will look like when finished:

        private void SendUpdates(ScheduleInfo Schedule)
        {

            if (ValueUpdated != null)
            {
                //create new instance of ValueUpdatedEventArgs
                //passing our local instance of ScheduleInfo
                //to the constructor

                ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(Schedule);

                //raise the event
                //valueArgs is an instance of ValueUpdatedEventArgs
                //and contains an instance of ScheduleInfo
                //which we want to pass to our main form (MainFrm)

                ValueUpdated(this, valueArgs);
            }//if
        }//SendUpdates

We call “SendUpdates” any time we want to send our data to the main form (MainFrm). Since we are using a button, we will call “SendUpdates” inside the “Click” event handler for the button. This is where we will get the information from our textboxes:

        private void addBtn_Click(object sender, EventArgs e)
        {
            //create new instance of ScheduleInfo
            _schedule = new ScheduleInfo();

            //get info from nameTextBox
            //and put in _schedule.Name
            _schedule.Name = nameTextBox.Text;

            //get info from eventTypeComboBox
            //and put in _schedule.EventType
            _schedule.EventType = eventTypeComboBox.Text;

            //call SendUpdates passing
            //our instance of ScheduleInfo
            SendUpdates(_schedule);
        }

“ChildFrm” should now look like this:

    public partial class ChildFrm : Form
    {
        //event interested parties can register with to know
        //when value is updated.
        //ValueUpdatedEventHandler is delegate defined in 
        //ValueUpdatedEventArgs

        public event ValueUpdatedEventHandler ValueUpdated;

        //create new instance of ScheduleInfo
        ScheduleInfo _schedule = new ScheduleInfo();

        public ChildFrm()
        {
            InitializeComponent();
        }

        private void addBtn_Click(object sender, EventArgs e)
        {
            //create new instance of ScheduleInfo
            _schedule = new ScheduleInfo();

            //get info from nameTextBox
            //and put in _schedule.Name
            _schedule.Name = nameTextBox.Text;

            //get info from eventTypeComboBox
            //and put in _schedule.EventType
            _schedule.EventType = eventTypeComboBox.Text;

            //call SendUpdates passing
            //our instance of ScheduleInfo
            SendUpdates(_schedule);
        }

        private void SendUpdates(ScheduleInfo Schedule)
        {

            if (ValueUpdated != null)
            {
                //create new instance of ValueUpdatedEventArgs
                //passing our local instance of ScheduleInfo
                //to the constructor

                ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(Schedule);

                //raise the event
                //valueArgs is an instance of ValueUpdatedEventArgs
                //and contains an instance of ScheduleInfo
                //which we want to pass to our main form (MainFrm)

                ValueUpdated(this, valueArgs);
            }//if
        }//SendUpdates

    }

We're almost done. Now, we will add two textboxes on MainFrm (named: textBox1 and textBox2) , a label (Text property = “Name:”), a label (Text property = “Event Type:”), and a button (named: openChildFrm1Btn).

6e295d636202e8557068b92e26bf6291

Double-click the button to create a "Click" event handler for the button.

The code for MainFrm should look like this:

    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
        }

        private void openChildFrm1Btn_Click(object sender, EventArgs e)
        {

        }
    }

We will use a List of type ScheduleInfo to hold our data.

Create a new List of type ScheduleInfo:

//create new List for ScheduleInfo
private List<ScheduleInfo> _myScheduleInfo = new List<ScheduleInfo>();

Create an instance of ChildFrm:

//create a new child form
private ChildFrm myChildFrm;

Now, the code should look like this:

    public partial class MainFrm : Form
    {

        //create new List for ScheduleInfo
        private List<ScheduleInfo> _myScheduleInfo = new List<ScheduleInfo>();

        //create a new child form
        private ChildFrm myChildFrm;


        public MainFrm()
        {
            InitializeComponent();
        }

        private void openChildFrm1Btn_Click(object sender, EventArgs e)
        {

        }
    }

Next, we will create the event handler method. This will be called every time the "ValueUpdated" event is raised in our ChildFrm.

We follow the same form as our delegate that is defined in "ValueUpdatedEventArgs.cs". "myChildFrm1_ValueUpdated" is what I chose to name the event handler--the name can be anything, but should be descriptive so we know what it is.

//event handler method
//this is called every time myChildFrm1.ValueUpdated event occurs
private void myChildFrm_ValueUpdated(object sender, ValueUpdatedEventArgs e)
{

}

An instance of ScheduleInfo is passed to "myChildFrm1_ValueUpdated" in parameter "e". Since “e” is an instance of “ValueUpdatedEventsArgs, and "Schedule" is an instance of ScheduleInfo (which contains our data). We would access Name, like this:

e.Schedule.Name

We want to create a new instance of ScheduleInfo every time the event handler is called and either add the data to our list or update the existing data if the entry already exists. Additionally, we will update TextBox1 and TextBox2 with the data we just received.

        //event handler method
        //this is called every time myChildFrm1.ValueUpdated event occurs
        private void myChildFrm_ValueUpdated(object sender, ValueUpdatedEventArgs e)
        {
            //used to determine if we need to
            //update our list or add to the
            //list
            Boolean scheduleExists = false;

            //check list to see if entry already exists

            for (int i = 0; i < _myScheduleInfoList.Count; i++)
            {
                //if "name" passed back from child forms exists,
                //in our list, update with the new information

                //"e" contains an instance of ValueUpdatedEventArgs.
                //"ValueUpdatedEventArgs" contains an instance of
                //ScheduleInfo in "Schedule".
                //ScheduleInfo contains "Name".
                if (String.Compare(_myScheduleInfoList[i].Name, e.Schedule.Name) == 0)
                {
                    //update 
                    _myScheduleInfoList[i] = e.Schedule;

                    //set scheduleExists = true
                    //so we know not to add
                    //schedule to the list
                    scheduleExists = true;

                    break; //exit loop
                }//if
            }//for

            //if name was not found, add _schedule
            //to _myScheduleInfoList
            if (scheduleExists == false)
            {
                //add _schedule to list
                //"e" contains an instance of ValueUpdatedEventArgs.
                //"ValueUpdatedEventArgs" contains an instance of
                //ScheduleInfo in "Schedule"
                _myScheduleInfoList.Add(e.Schedule);
            }//if

            //set text in textBox1 to Name
            textBox1.Text = e.Schedule.Name;

            //set text in textBox2 to EventType
            textBox2.Text = e.Schedule.EventType;


            //print out our list.
            //This is for demonstration purposes.
            //You might update a file here instead, or
            //choose to do nothing else

            Console.WriteLine();

            foreach (ScheduleInfo sched in _myScheduleInfoList)
            {
                Console.WriteLine("Name: " + sched.Name + " Event Type: " + sched.EventType);
            }//foreach

        }//myChildFrm_ValueUpdated

Lastly, we need to add code for when the "openChildFrm1Btn" button is clicked. We want to create a new instance of the form (ChildFrm), add a handler / listener to handle the "ValueUpdated" event in ChildFrm, and then show the form.

        private void openChildFrm1Btn_Click(object sender, EventArgs e)
        {
            //create new instance of ChildFrm
            myChildFrm = new ChildFrm();

            //add listener / event handler
            myChildFrm.ValueUpdated += new ValueUpdatedEventHandler(myChildFrm_ValueUpdated);

            //show myChildFrm
            myChildFrm.Show();
        }

Here's the final version of "MainFrm.cs":

        public partial class MainFrm : Form
        {

            //create new List for ScheduleInfo
            private List<ScheduleInfo> _myScheduleInfoList = new List<ScheduleInfo>();

            //create a new child form
            private ChildFrm myChildFrm;


            public MainFrm()
            {
                InitializeComponent();
            }

            private void openChildFrm1Btn_Click(object sender, EventArgs e)
            {
                //create new instance of ChildFrm
                myChildFrm = new ChildFrm();

                //add listener / event handler
                myChildFrm.ValueUpdated += new ValueUpdatedEventHandler(myChildFrm_ValueUpdated);

                //show myChildFrm
                myChildFrm.Show();
            }

            //event handler method
            //this is called every time myChildFrm1.ValueUpdated event occurs
            private void myChildFrm_ValueUpdated(object sender, ValueUpdatedEventArgs e)
            {
                //used to determine if we need to
                //update our list or add to the
                //list
                Boolean scheduleExists = false;

                //check list to see if entry already exists

                for (int i = 0; i < _myScheduleInfoList.Count; i++)
                {
                    //if "name" passed back from child forms exists,
                    //in our list, update with the new information

                    //"e" contains an instance of ValueUpdatedEventArgs.
                    //"ValueUpdatedEventArgs" contains an instance of
                    //ScheduleInfo in "Schedule".
                    //ScheduleInfo contains "Name".
                    if (String.Compare(_myScheduleInfoList[i].Name, e.Schedule.Name) == 0)
                    {
                        //update 
                        _myScheduleInfoList[i] = e.Schedule;

                        //set scheduleExists = true
                        //so we know not to add
                        //schedule to the list
                        scheduleExists = true;

                        break; //exit loop
                    }//if
                }//for

                //if name was not found, add _schedule
                //to _myScheduleInfoList
                if (scheduleExists == false)
                {
                    //add _schedule to list
                    //"e" contains an instance of ValueUpdatedEventArgs.
                    //"ValueUpdatedEventArgs" contains an instance of
                    //ScheduleInfo in "Schedule"
                    _myScheduleInfoList.Add(e.Schedule);
                }//if

                //set text in textBox1 to Name
                textBox1.Text = e.Schedule.Name;

                //set text in textBox2 to EventType
                textBox2.Text = e.Schedule.EventType;


                //print out our list.
                //This is for demonstration purposes.
                //You might update a file here instead, or
                //choose to do nothing else

                Console.WriteLine();

                foreach (ScheduleInfo sched in _myScheduleInfoList)
                {
                    Console.WriteLine("Name: " + sched.Name + " Event Type: " + sched.EventType);
                }//foreach

            }//myChildFrm_ValueUpdated
        }

The short version:
1. Create a new project (select "Windows Forms Application")
2. Right-click "Form1.cs" in Solution Explorer and choose "Rename". Rename it to "MainFrm.cs". You should be prompted, "You are renaming a file. Would you like to perform a rename in this project of all references....?" Click, "Yes".
3. Add two textboxes (named: textBox1 and textBox2) and one button (named: openChildFrm1Btn) to MainFrm.

6e295d636202e8557068b92e26bf6291

Double-click the button. It will create "private void openChildFrm1Btn_Click…"

Replace the code in MainFrm with the following code:

    // MainFrm.cs
    //
    // Subject: form communication
    //
    // Description:
    // This example shows how to send data from one form (ChildFrm)
    // to another form (MainFrm). It uses two user-defined classes,
    // a delegate, an event, and an event listener / handler.
    //
    // Notes:
    // This example requires two textboxes on MainFrm 
    // (named: textBox1 and textBox2)

    public partial class MainFrm : Form
    {

        //create new List for ScheduleInfo
        private List<ScheduleInfo> _myScheduleInfoList = new List<ScheduleInfo>();

        //create a new child form
        private ChildFrm myChildFrm;


        public MainFrm()
        {
            InitializeComponent();
        }

        private void openChildFrm1Btn_Click(object sender, EventArgs e)
        {
            //create new instance of ChildFrm
            myChildFrm = new ChildFrm();

            //add listener / event handler
            myChildFrm.ValueUpdated += new ValueUpdatedEventHandler(myChildFrm_ValueUpdated);

            //show myChildFrm
            myChildFrm.Show();
        }

        //event handler method
        //this is called every time myChildFrm1.ValueUpdated event occurs
        private void myChildFrm_ValueUpdated(object sender, ValueUpdatedEventArgs e)
        {
            //used to determine if we need to
            //update our list or add to the
            //list
            Boolean scheduleExists = false;

            //check list to see if entry already exists

            for (int i = 0; i < _myScheduleInfoList.Count; i++)
            {
                //if "name" passed back from child forms exists,
                //in our list, update with the new information

                //"e" contains an instance of ValueUpdatedEventArgs.
                //"ValueUpdatedEventArgs" contains an instance of
                //ScheduleInfo in "Schedule".
                //ScheduleInfo contains "Name".
                if (String.Compare(_myScheduleInfoList[i].Name, e.Schedule.Name) == 0)
                {
                    //update 
                    _myScheduleInfoList[i] = e.Schedule;

                    //set scheduleExists = true
                    //so we know not to add
                    //schedule to the list
                    scheduleExists = true;

                    break; //exit loop
                }//if
            }//for

            //if name was not found, add _schedule
            //to _myScheduleInfoList
            if (scheduleExists == false)
            {
                //add _schedule to list
                //"e" contains an instance of ValueUpdatedEventArgs.
                //"ValueUpdatedEventArgs" contains an instance of
                //ScheduleInfo in "Schedule"
                _myScheduleInfoList.Add(e.Schedule);
            }//if

            //set text in textBox1 to Name
            textBox1.Text = e.Schedule.Name;

            //set text in textBox2 to EventType
            textBox2.Text = e.Schedule.EventType;


            //print out our list.
            //This is for demonstration purposes.
            //You might update a file here instead, or
            //choose to do nothing else

            Console.WriteLine();

            foreach (ScheduleInfo sched in _myScheduleInfoList)
            {
                Console.WriteLine("Name: " + sched.Name + " Event Type: " + sched.EventType);
            }//foreach

        }//myChildFrm_ValueUpdated
    }

Create "ScheduleInfo.cs"
1. In menu bar, click "Project"
2. Select "Add New Item"
3. Select "Class". In name, type: "ScheduleInfo.cs"
4. Click "Add"
5. Replace the code in "ScheduleInfo.cs" with the following code (this uses Option #3 above):

    // ScheduleInfo.cs
    //
    // Subject: form communication
    //
    // Description:
    // An instance of this class is used to pass data
    // from one form to another.

    public class ScheduleInfo
    {

        private string _name = string.Empty;
        private string _eventType = string.Empty;

        //Property Name
        public string Name
        {
            get
            {
                return this._name;
            } //get

            set
            {
                this._name = value;
            } //set
        } //Name

        //Property EventType
        public string EventType
        {
            get
            {
                return this._eventType;
            } //get

            set
            {
                this._eventType = value;
            } //set
        } //EventType

    }

Create "ValueUpdatedEventArgs.cs"
1. In menu bar, click "Project"
2. Select "Add New Item"
3. Select "Class". In name, type: "ValueUpdatedEventArgs.cs"
4. Click "Add"
5. Replace the code in "ValueUpdatedEventArgs.cs" with the following code (this uses option #3 above):

    // ValueUpdatedEventArgs.cs
    //
    // Subject: form communication
    //
    // Description:
    // This class is used to pass data from one form to
    // another. It inherits from System.EventArgs and 
    // contains an instance of ScheduleInfo.
    // This is also where we declare our delegate.

    public delegate void ValueUpdatedEventHandler(object sender, ValueUpdatedEventArgs e);

    public class ValueUpdatedEventArgs : System.EventArgs
    {
        //instance of ScheduleInfo
        private ScheduleInfo _schedule;


        public ValueUpdatedEventArgs(ScheduleInfo Schedule)
        {
            this._schedule = Schedule;
        }//constructor


        //ReadOnly Property Schedule
        public ScheduleInfo Schedule
        {
            get
            {
                return this._schedule;
            }//get
        }//Schedule

    }

Create "ChildFrm.cs"
1. In menu bar, click "Project"
2. Select "Add New Item"
3. Select "Windows Form". In name, type: "ChildFrm.cs"
4. Click "Add"
5. Add one TextBox (named: TextBox1), one ComboBox (named: eventTypeComboBox), and one button (named: addBtn) to ChildFrm.

d269ae20b6901421620f899eba6aa249

Double-click the button. It will create "private void addBtn_Click…"

Replace the code in "ChildFrm.cs" with the following code:

    // ChildFrm.cs
    //
    // Subject: form communication
    //
    // Description:
    // This is the child form (ChildFrm). It uses an event
    // to pass its data back to the calling form (MainFrm).
    // It uses an instance of ValueUpdatedEventArgs
    // which contains an instance of ScheduleInfo
    // to pass the data.

    public partial class ChildFrm : Form
    {
        //event interested parties can register with to know
        //when value is updated.
        //ValueUpdatedEventHandler is delegate defined in 
        //ValueUpdatedEventArgs

        public event ValueUpdatedEventHandler ValueUpdated;

        //create new instance of ScheduleInfo
        ScheduleInfo _schedule = new ScheduleInfo();

        public ChildFrm()
        {
            InitializeComponent();
        }

        private void addBtn_Click(object sender, EventArgs e)
        {
            //create new instance of ScheduleInfo
            _schedule = new ScheduleInfo();

            //get info from nameTextBox
            //and put in _schedule.Name
            _schedule.Name = nameTextBox.Text;

            //get info from eventTypeComboBox
            //and put in _schedule.EventType
            _schedule.EventType = eventTypeComboBox.Text;

            //call SendUpdates passing
            //our instance of ScheduleInfo
            SendUpdates(_schedule);
        }

        private void SendUpdates(ScheduleInfo Schedule)
        {

            if (ValueUpdated != null)
            {
                //create new instance of ValueUpdatedEventArgs
                //passing our local instance of ScheduleInfo
                //to the constructor

                ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(Schedule);

                //raise the event
                //valueArgs is an instance of ValueUpdatedEventArgs
                //and contains an instance of ScheduleInfo
                //which we want to pass to our main form (MainFrm)

                ValueUpdated(this, valueArgs);
            }//if
        }//SendUpdates

    }

Note: One could easily modify this to use a DataGridView instead of TextBox (other possible modifications also exist).

castajiz_2 commented: Well done!! +4
ddanbe commented: Great stuff! Must have missed it. Thanks. +15
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Nice tutorial. I'll also add that there are usually two situations where forms communicate that affect your choice of how to do it:

  1. The forms are not modal and the lifetime of the child form is either long or independent of the code that creates it. In this case the event approach is suitable.

  2. The child form represents a modal dialog. In this case two way events are overengineered; a better approach uses public properties and is vastly simpler:

    using (var dlg = new ChildForm())
    {
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            // Whatever other stuff you want to do...
    
            textBox1.Text = dlg.Name;
            textBox2.Text = dlg.EventType;
        }
    }
    

Your tutorial covers the first case quite well, but doesn't cover the second. I just wanted to point that out for readers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.