Open a second form to enter data and have it saved in first form

By Peter Bromberg

This is basic stuff, but we get a lot of forum posts asking how to open a second form to enter data, not be able to return to the first form until you close the second form, and have the data you added updated in the first form. Code provided is for each form. Form1 has a DataGridView and a button. When loaded, it displays some sample data. When you click the button, the second form is shown as a dialog. You can enter a new item, and it will be saved and updated in the display on the first form

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

namespace TwoForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
             InitializeComponent();
        }

         public List<Person> PersonData = new List<Person>();

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.FirstForm = this;
            form2.ShowDialog();
        }

         public void BindGrid()
        {
             this.dataGridView1.DataSource = null;
            this.dataGridView1.DataSource = PersonData;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
             GetSampleData();
            BindGrid();
        }

         private void GetSampleData()
        {
             PersonData.Add(new Person() {Name="Joe Blow", Email="jblow@coolio.com"});
            PersonData.Add(new Person() { Name = "Jane Doe", Email = "jdoe@coolio.com" });
        }
     }
}

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

namespace TwoForms
{
    public partial class Form2 : Form
    {

         public Form1 FirstForm { get; set; }
        public Form2()
        {
             InitializeComponent();
        }

         private void button1_Click(object sender, EventArgs e)
        {
            Person p = new Person() {Name = txtName.Text, Email = txtEmail.Text};
            FirstForm.PersonData.Add(p);
            FirstForm.BindGrid();
            this.Close();
        }
     }
}

Open a second form to enter data and have it saved in first form  (757 Views)